微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

嵌入在 UIViewController 中的 UIHostingController - 如何从外部更新 @State?

如何解决嵌入在 UIViewController 中的 UIHostingController - 如何从外部更新 @State?

我正在使用 UIHostingControllerContentView 嵌入 ViewController。我想在按下“更改名称”按钮时更改 ContentViewname名称。这是我的代码

class ViewController: UIViewController {

    var contentView: ContentView? /// keep reference to ContentView
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.secondarySystemBackground
        
        /// add the button
        let button = UIButton()
        button.frame = CGRect(x: 50,y: 50,width: 200,height: 100)
        button.setTitle("Change name",for: .normal)
        button.setTitleColor(.blue,for: .normal)
        button.addTarget(self,action: #selector(handleTap),for: .touchUpInside)
        view.addSubview(button)
        
        /// add the SwiftUI ContentView
        let contentView = ContentView()
        let hostingController = UIHostingController(rootView: contentView)
        self.contentView = contentView
        
        addChild(hostingController)
        view.insertSubview(hostingController.view,at: 0)
        hostingController.view.frame = CGRect(x: 0,y: 400,width: view.bounds.width,height: view.bounds.height - 400)
        hostingController.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        hostingController.didMove(toParent: self)
    }
    
    @objc func handleTap() {
        contentView?.updateLastCardName(name: "Updated name") /// update the name
    }
}

struct ContentView: View {
    @State var name = "Name"

    var body: some View {
        Text(name)
    }

    func updateLastCardName(name: String) {
        print("updating to \(name)")
        self.name = name /// but it's not updating!
    }
}

结果:

问题是,即使 func updateLastCardName(name: String) {调用,当我设置 self.name = name 时也没有变化。 Text 继续显示名称”,而不是“更新的名称”。

我已经阅读了 @State should be local,所以我尝试使用 updateLastCardName 函数解决这个问题。但是,它不起作用。我的方法有问题吗?

如何从ContentView更新name的{​​{1}}?

解决方法

var contentView: ContentView? /// keep reference to ContentView

这是错误的假设,因为 ContentView 是一个结构体,即。值,因此您保留副本而不是参考。

相反,我们应该使用视图模型类的实例作为从 UIKit 到 SwiftUI 通信的参考。在下面找到带有方法演示的修改代码。

使用 Xcode 12.4 / iOS 14.4 测试

class ViewModel: ObservableObject {
    @Published var name = "Name"
}

class ViewController: UIViewController {

    private var vm: ViewModel!

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.secondarySystemBackground

        /// add the button
        let button = UIButton()
        button.frame = CGRect(x: 50,y: 50,width: 200,height: 100)
        button.setTitle("Change name",for: .normal)
        button.setTitleColor(.blue,for: .normal)
        button.addTarget(self,action: #selector(handleTap),for: .touchUpInside)
        view.addSubview(button)

        /// add the SwiftUI ContentView
        self.vm = ViewModel()
        let contentView = ContentView(vm: self.vm)
        let hostingController = UIHostingController(rootView: contentView)

        addChild(hostingController)
        view.insertSubview(hostingController.view,at: 0)
        hostingController.view.frame = CGRect(x: 0,y: 400,width: view.bounds.width,height: view.bounds.height - 400)
        hostingController.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        hostingController.didMove(toParent: self)
    }

    @objc func handleTap() {
        vm.name = "Updated name" /// update the name
    }
}

struct ContentView: View {
    @ObservedObject var vm: ViewModel

    var body: some View {
        Text(vm.name)
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?