快速从PopUp视图控制器中识别当前视图控制器

时间:2019-05-17 08:52:40

标签: ios swift

假设我们有2个视图控制器

  1. FirstViewController.swift
  2. PopUpViewContraller.swift

PopUpViewContraller已加载到FirstViewController上。现在,我该如何从PopUpViewContraller的FirstViewController中调用一个函数。

3 个答案:

答案 0 :(得分:1)

谢谢您回答我的问题。

最后,我得到了上述问题的解决方案。

我们可以使用通知中心解决此问题。

1)在弹出视图控制器()

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "botIsRemoved"), object: self)

2)在第一个视图控制器中

inside viewDidLoard()

NotificationCenter.default.addObserver(self, selector: #selector(removeBotNow), name: NSNotification.Name(rawValue: "botIsRemoved"), object: nil)

并添加以下功能

@objc func removeBotNow(notification : Notification){

        // your tasks

    }

答案 1 :(得分:0)

使用本机Swift协议:

protocol masterGreeting {
    func sayHi()
}

class FirstVC: UIViewController, masterGreeting {
      func sayHi() {
        print("Hi")
      }


    // When you present PopUpViewController
    func displaySecondVC() {
       let vc = secondController()
       vc.delegate = self
       self.present(vc, animated: true)
    }

} 

在您的PopUpViewController中:

class PopUpViewController: UIViewController {
    var delegate: masterGreeting?

     self.delegate?.sayHi() // Say HI


}

还有更多有关Protocols的信息:

Protocols — The Swift Programming Language (Swift 5) - Swift.org

答案 2 :(得分:0)

另一种方法:

使用 closures 使其正常运行。 Apple closures中广泛使用了Swift

  1. closure中创建PopUpViewContraller变量
  2. 在显示closure时,从FirstViewController中设置PopUpViewContraller
  3. 关闭closure时致电PopUpViewContraller

示例:

class FirstViewController: UIViewController {
    @IBAction func openPopupVC(_ sender: Any) {
        if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PopUpViewContraller") as? PopUpViewContraller {
            controller.handler = {[weak self] in
                self?.callFromHandler()
            }
            self.present(controller, animated: true, completion: nil)
        }
    }

    func callFromHandler() {
        print("Working..!!!")
    }
}

class PopUpViewContraller: UIViewController {
    var handler: (()->())?

    @IBAction func saveButton(_ sender: Any) {
        self.dismiss(animated: true) {
            self.handler?()
        }
    }
}
当然,

代表是另一种方式。您可以采用任何一种方法。