将 UIHostingController 与 SwiftUI 的 View 一起使用时,如何解析“super.init”调用之前使用的“self”?

问题描述 投票:0回答:1

我有以下代码,我希望我的

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

我可以知道解决此类问题的好方法是什么吗?谢谢。

swift swiftui uikit
1个回答
0
投票

为操作指定一个空的默认值,然后在 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) }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.