2017-07-21 207 views
-2

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

我试图使用preparesegue函数,但我无法得到我发现工作的代码。

+0

你真的需要触碰插座或你只需要通知有关点击? –

+0

我真的不知道..我的父视图是一个带有3个按钮的过滤器菜单,它们充当单选按钮,两个开关和一个“应用过滤器”按钮。所以,我需要知道用户何时选择应用过滤器,然后选择做出选择。 @PhillipMills – bloop

+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) 
} 
相关问题