我有以下代码,我希望我的
SwiftUI
执行 UIKit
关闭函数。
struct FlashcardView: View {
var closeAction: () -> Void
var body: some View {
NavigationView {
Text("This is the main content")
.navigationTitle("Your Title")
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button(action: { closeAction() }) {
Image(systemName: "xmark")
.foregroundColor(.blue)
}
}
}
}
}
}
class FlashcardHostingController: UIHostingController<FlashcardView> {
required init?(coder: NSCoder) {
let rootView = FlashcardView(closeAction: { [weak self] in
self?.dismiss(animated: true, completion: nil)
})
super.init(coder: coder, rootView: rootView)
}
}
但是,我收到编译器错误
'self' used before 'super.init' call
我可以知道解决此类问题的好方法是什么吗?谢谢。
为操作指定一个空的默认值,然后在 init 中单独设置
struct FlashcardView: View {
var closeAction: () -> Void = { }
//...
}
class FlashcardHostingController: UIHostingController<FlashcardView> {
required init?(coder: NSCoder) {
var rootView = FlashcardView()
super.init(coder: coder, rootView: rootView)
rootView.closeAction = { [weak self] in self?.dismiss(animated: true, completion: nil) }
}
}