当控件/状态在SecondViewController中时,我如何调用另一个firstViewController swift文件中的函数/方法。 在第二个ViewController中,当按下按钮时,secondViewController应调用firstViewController中的函数,并将控件/状态传输到从secondViewController推送到的thirdViewController。
secondViewController Button Action
@IBAction func EnterGallery(_ sender: Any){
// Want to invoke EnterGallery function in firstViewController and dismiss from secondViewController
self.dismiss(animated: true, completion: nil)}
firstViewController pushViewController function
func EnterGallery() {
let dest = self.storyboard?.instantiateViewController(withIdentifier:
"GalleryViewController") as! GalleryViewController // thirdViewController
self.navigationController?.pushViewController(dest, animated: true)
}
请注意:我不会将任何数据从secondViewController传递到FirstViewController。 我只想让我的firstViewController推送到thirdViewController,而我只想从firstViewController用当前函数提供的secondViewController中删除secondViewController。 一旦我从secondViewController中删除,我希望我的屏幕直接转到ThirdViewController。
基本上,我只想调用另一个ViewController中的函数,而不需要从初始ViewController传递任何数据。 所以我不能使用协议和委托,通知和观察器。 我该如何处理这个问题? 还有许多其他情况下,我需要使用这个类似的功能。 所以我不确定如何准确地执行这个。 由于我是Swift的新手,任何帮助都将不胜感激。 提前谢谢你。
您的viewController应该了解其他viewController,并且应该能够与它们交互。
这里有一篇关于在viewControllers之间传递数据(或者只是在viewControllers之间进行交互--随你喜欢)的好文章
最常见的做法是委托模式。 用两个词来形容代表团:
创建委托协议:
protocol MyDelegate {
func doSmth()
}
将委托属性添加到ViewController
中,该属性将触发AnotherViewController
中的某些内容:
var delegate: MyDelegate?
AnotherViewController
应符合MyDelegate
协议:
class anotherViewController: MyDelegate {
func doSmth() {
print("I am doing something")
}
}
然后将符合MyDelege
协议的类分配到此属性中
viewController.delegate = anotherViewController
就是这样! 现在您可以在ViewController
中触发委托方法
delegate.doSmth()
Google委托模式。 yt:https://youtu.be/dbwu6tnhley希望这能帮到你。 顺便说一下,委托模式可以工作,即使您不想在两者之间传递数据。