我有此代码:
MainViewControler:
class MainViewControler: UIViewController, ContainerToMaster {
@IBOutlet weak var systemContainerView: UIView!
@IBOutlet weak var favoriteProductBtn2: UIButton!
weak var containerViewController: Calculator1ViewController?
func changeBtn() {
favoriteProductBtn2.isHidden = true
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
}
CallculatorViewController:
@IBOutlet weak var containerView: UIView!
class CallculatorViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
Calculator1ViewController:
protocol ContainerToMaster {
func changeBtn()
}
class Calculator1ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
containerToMaster?.changeBtn()
}
}
我有这样的应用程序布局:
主视图= MainViewControler
。
在MainViewControler
中,我有一个MainViewControler
所在的containerView(systemContainerView)
在CallculatorViewController
中,我有Calculator1ViewController
所在的下一个containerView。
输入Calculator1ViewController
时,应启动功能:containerToMaster?.changeBtn()
(应在MainViewControler
中工作)。
问题是-此功能不起作用:(
有人知道如何解决吗?
答案 0 :(得分:1)
一个包含的viewController嵌入了 embed segue 。您需要覆盖prepare(for:sender)
并将self
设置为目标viewController中的containerToMaster
委托。由于在另一个容器视图中嵌入了一个容器视图,因此情况变得复杂,因此您需要设置两个委托并传递按钮回调:
protocol ContainerToMaster {
func changeBtn()
}
class MainViewControler: UIViewController, ContainerToMaster {
@IBOutlet weak var systemContainerView: UIView!
@IBOutlet weak var favoriteProductBtn2: UIButton!
weak var containerViewController: Calculator1ViewController?
func changeBtn() {
favoriteProductBtn2.isHidden = true
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destination as? CallculatorViewController {
destVC.containerToMaster = self
}
}
}
class CallculatorViewController: UIViewController, ContainerToMaster {
weak var containerToMaster: ContainerToMaster?
override func viewDidLoad() {
super.viewDidLoad()
}
func changeBtn() {
// pass the button call back
containerToMaster?.changeBtn()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destVC = segue.destination as? Calculator1ViewController {
destVC.containerToMaster = self
}
}
}
class Calculator1ViewController: UIViewController {
weak var containerToMaster: ContainerToMaster?
override func viewDidLoad() {
super.viewDidLoad()
containerToMaster?.changeBtn()
}
}