【问题标题】:Accessing parent view buttons in container view controller访问容器视图控制器中的父视图按钮
【发布时间】:2017-12-27 20:15:48
【问题描述】:

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

我尝试使用 preparesegue 函数,但我发现的代码无法正常工作。

【问题讨论】:

  • 您真的需要接触网点还是只需要了解点击次数?
  • 老实说,我不确定.. 我的父视图是一个过滤器菜单,其中包含 3 个用作单选按钮的按钮、两个开关和一个“应用过滤器”按钮。所以,我需要知道用户何时选择应用过滤器,然后做出了哪些选择。 @菲利普米尔斯
  • 听起来好像父级只需要将其控制动作转发给包含的视图控制器。

标签: ios swift3 collectionview uicontainerview


【解决方案1】:

一种选择是使用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)
}

【讨论】:

    猜你喜欢
    • 2012-10-26
    • 2012-10-28
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2014-02-10
    相关资源
    最近更新 更多