访问容器视图控制器中的父视图按钮

时间:2017-07-21 17:24:19

标签: ios swift3 collectionview uicontainerview

我在容器视图中有一个集合视图控制器和父视图上的按钮 - 我需要我的容器视图才能从我的父视图访问按钮出口,以便我可以检测何时单击按钮以便修改我的集合视图(在容器视图中)相应的。

我尝试使用preparesegue功能,但我无法获得我发现的代码。

1 个答案:

答案 0 :(得分:0)

一种选择是使用NotificationCenter,让您的按钮发布通知,并让您的子视图控制器听取它们。

例如,在父VC中,在点击按钮时调用的函数中发布通知,如下所示:

@IBAction func buttonTapped(_ sender: UIButton) {
     NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil, userInfo: nil)
}

在需要响应按钮点击的子VC中,将以下代码放在viewWillAppear:中以将VC设置为该特定通知的侦听器:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(handleButtonTap(_:)), name: NSNotification.Name(rawValue: "ButtonTapped"), object: nil)
}

在同一个视图控制器中,添加上面提到的handleButtonTap:方法。当“ButtonTapped”通知进入时,它将执行此方法。

@objc func handleButtonTap(_ notification: NSNotification) {
    //do something when the notification comes in
}

不要忘记在不再需要视图控制器时将其删除,如下所示:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}
相关问题