假设我们有2个视图控制器
PopUpViewContraller已加载到FirstViewController上。现在,我该如何从PopUpViewContraller的FirstViewController中调用一个函数。
答案 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
。
closure
中创建PopUpViewContraller
变量closure
时,从FirstViewController
中设置PopUpViewContraller
。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?()
}
}
}
当然,代表是另一种方式。您可以采用任何一种方法。