【问题标题】:Handling @IBOutlet in UIViewControllerRepresentable在 UIViewControllerRepresentable 中处理 @IBOutlet
【发布时间】:2021-08-01 19:30:58
【问题描述】:

我正在尝试将 Apple 演示中的 ViewController 包装在 SwiftUI UIViewControllerRepresentable 中,它有一组连接到主情节提要的 IBOutlets。我该如何处理这种情况?应该将 IBOutlets 替换为 View 结构,还是应该尝试将 Storyboard 与 SwiftUI 合并?

struct ARViewContainer: UIViewControllerRepresentable {
    
    @ObservedObject var model: Model
    
    typealias UIViewControllerType = ARView
    
    func makeUIViewController(context: Context) -> ARView {
        return ARView(model)
    }
    func updateUIViewController(_ uiViewController:
        ARViewContainer.UIViewControllerType, context:
        UIViewControllerRepresentableContext<ARViewContainer>) { }
    
}

class ARView: UIViewController, ARSCNViewDelegate {
    
    @ObservedObject var model: Model
    
    // MARK: IBOutlets
    
    @IBOutlet var sceneView: VirtualObjectARView!
    
    @IBOutlet weak var addObjectButton: UIButton!
    
    @IBOutlet weak var blurView: UIVisualEffectView!
    
    @IBOutlet weak var spinner: UIActivityIndicatorView!
    
    @IBOutlet weak var upperControlsView: UIView!

【问题讨论】:

    标签: swiftui uikit


    【解决方案1】:

    它绝对可以工作,但您必须从情节提要中实例化您的UIViewController。现在,你只是用ARView() 初始化它,所以它没有连接到情节提要,也没有办法连接出口。

    基本示例:

    struct ContentView : View {
        var body: some View {
            MyStoryboardVCRepresented()
        }
    }
    
    struct MyStoryboardVCRepresented : UIViewControllerRepresentable {
        func makeUIViewController(context: Context) -> MyStoryboardVC {
            UIStoryboard(name: "MyStoryboard", bundle: Bundle.main).instantiateViewController(identifier: "MyVC") as! MyStoryboardVC //theoretically unsafe to unwrap like this with `!`, but we know it works, since the view controller is included in the storyboard
        }
        
        func updateUIViewController(_ uiViewController: MyStoryboardVC, context: Context) {
            uiViewController.label.text = "Hello, world!"
        }
    }
    
    class MyStoryboardVC : UIViewController {
        @IBOutlet var label : UILabel!
    }
    

    【讨论】:

    • 谢谢!简明扼要
    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多