我正在使用 aUIHostingController
嵌入其中ContentView
。当按下“更改名称”按钮时,ViewController
我想更改ContentView
's的名称。name
这是我的代码:
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
应该是 local,所以我尝试使用该updateLastCardName
功能解决这个问题。但是,它不起作用。我的方法错了吗?
如何更新来自ContentView
?name
ViewController