我需要VC3才能向VC1发送函数调用!
我了解委派的基础知识,我刚刚阅读了有关如何在没有prepareForSegue的情况下分配委托的指南:
Swift Delegate Between Two VCs Without Segue
但是如果两个之间需要对话的VC该怎么办?例如,VC1呈现VC2,VC2呈现VC3。 VC3希望VC1做一些工作。在没有问题的情况下,在VC2中发生编程式VC3调用,我该如何实现?
最佳答案
好吧,如果您想继续使用委托模式,则需要更新VC2以传递引发委托回调。
因此,使用您发布的该示例中的代码:
ViewControllerOne :
class ViewControllerOne: UIViewController,testProtocol {
@IBAction func btInit(sender: AnyObject) {
println("Bt Init")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController2: ViewControllerTwo = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as ViewControllerTwo
viewController2.viewController1 = self
self.presentViewController(initViewController,animated: false, nil)
}
func testDelegate(){
println(" in my view controller delegate ")
}
}
ViewControllerTwo :
class ViewControllerTwo: UIViewController,testProtocol {
var viewController1: ViewControllerOne? = ViewControllerOne()
@IBAction func btInit(sender: AnyObject) {
println("Bt Init")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController3: ViewControllerThree = storyBoard.instantiateViewControllerWithIdentifier("viewTarget") as ViewControllerThree
viewController3.delegate = viewController1
self.presentViewController(initViewController,animated: false, nil)
}
}
ViewControllerThree :
protocol testProtocol {
func testDelegate() // this function the first controllers
}
class ViewControllerThree: UIViewController {
@IBAction func BtTarget(sender: AnyObject) {
println("bt target pressed")
delegate?.testDelegate()
}
var delegate : testProtocol?
}
更好的选择
我个人不喜欢这种方法,因为它在其他需要通信的两个VC的
ViewControllerTwo
上添加了不必要的耦合,因此IMO更好的替代方法是通过使用NSNotification
使用Observer模式,以便VC1注册为侦听器通知,然后在以后的某个时间,VC3发布该通知(以及可选的任何数据),VC1接收该通知并执行所需的任何操作。关于ios - 分配代表而不进行Segue或程序调用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34072932/