代码之家  ›  专栏  ›  技术社区  ›  bloop

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

  •  -2
  • bloop  · 技术社区  · 8 年前

    我试图使用preparesegue函数,但我无法获得我找到的代码。

    1 回复  |  直到 8 年前
        1
  •  0
  •   JAB    8 年前

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

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

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

    在需要响应按钮点击的子VC中,将以下代码放入 viewWillAppear:

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

    在同一视图控制器中,添加 handleButtonTap:

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

    当不再需要视图控制器时,不要忘记将其作为观察者删除,如下所示:

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