我有带主视图和子视图的UIViewController。
我要从ChildView更改mainView中的标签
我添加的子项
let to = ChildView()
self.addChild(to)
self.mainView.addSubview(to.view)
self.mainViewConstraint.constant = to.view.frame.height
to.view.frame = self.mainView.bounds
to.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
mainView-它的视图,其中显示childView
我试着和代表一起做
在ChildView中:
protocol UserDelegate {
func changeName(name: String)
}
class ChildView: UIViewController {
var userDelegate: UserDelegate?
@IBAction func changeNameBtn(_ sender: UIButton) {
self.userDelegate?.changeName(name: "TestChanges")
}
}
在主视图中:
class MainView: UIViewController, UserDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let ChildView = ChildView()
ChildView.userDelegate = self
}
func changeName(name: String) {
self.helloLabel.text = "Hello \(name)!"
}
}
最佳答案
问题是您呈现ChildView
的一个实例,并在ChildView
的另一个实例上设置委托。因此,屏幕上显示的子视图与调用委托的子视图不同。添加ChildView
时设置代理:
let to = ChildView()
self.addChild(to)
self.mainView.addSubview(to.view)
self.mainViewConstraint.constant = to.view.frame.height
// set the delegate here
to.userDelegate = self.mainView
to.view.frame = self.mainView.bounds
to.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
此外,要防止保留循环,请使用对委托的引用:
protocol UserDelegate: AnyObject {
func changeName(name: String)
}
class ChildView: UIViewController {
weak var userDelegate: UserDelegate?
@IBAction func changeNameBtn(_ sender: UIButton) {
self.userDelegate?.changeName(name: "TestChanges")
}
}
最后,您可以从主视图中删除
weak
实现:class MainView: UIViewController, UserDelegate {
// this should be enough
func changeName(name: String) {
self.helloLabel.text = "Hello \(name)!"
}
}
关于swift - 委托(delegate)从 subview 到主 View 的更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55947999/