首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在UIViewControllerRepresentable中处理@IBOutlet

在UIViewControllerRepresentable中处理@IBOutlet
EN

Stack Overflow用户
提问于 2021-08-01 19:30:58
回答 1查看 123关注 0票数 1

我正在尝试将苹果演示中的一个ViewController包装在SwiftUI UIViewControllerRepresentable中,它有一组IBOutlets,它们连接到主故事板。我该如何处理这种情况?应该将IBOutlets替换为视图结构,还是应该尝试将情节提要与SwiftUI结合起来?

代码语言:javascript
复制
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!
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-08-01 20:22:13

它肯定可以工作,但你必须从故事板实例化你的UIViewController。现在,您只是使用ARView()对其进行初始化,因此它无法连接到故事板,也无法连接插座。

基本示例:

代码语言:javascript
复制
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!
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68613728

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档