如何使用未直接连接的viewcontroller的协议和委托方法?

时间:2018-02-23 10:07:15

标签: swift delegates protocols

我是swift和iOS开发的新手。我对协议和委托方法有疑问。

我有4个vc,例如vc1,vc2,vc3,vc4。我从vc1-> vc2-> vc3-vc4-> vc1导航。那是从vc4开始,我使用导航控制器回到vc1。

我有一个协议和方法,如

protocol myProtocol{

func myFunc()

}

在vc4中,我将代表作为,

var delegate:myProtocol?

我在按钮操作中使用它

if let delegate = self.delegate{

delegate.myFunc()
}

并将vc4弹回vc1。

现在在VC1中,我将myProtocol扩展为

class vc1:myProtocol{

override func viewDidLoad()
{

let vcProtocol = vc4()
vc4.delegate = self

}

func myFunc()
{
print("executing this")

}

}

但它不起作用。我可以这样做吗? 如何使用委托和协议将这些连接到类。请帮助我

3 个答案:

答案 0 :(得分:0)

如果控制器没有被销毁,

viewDidLoad只执行一次。

例如,尝试在viewWillAppear中调用。

此外,您无需更改vc4的委托,只需将委托再次设置为vc1(在viewWillAppear中)。

答案 1 :(得分:0)

你试过通知吗? 在VC1 ViewController ViewDidLoad方法中:

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

在VC4中需要myFunc时:

NotificationCenter.default.post(name: Notification.Name("aNotificationName"), object: nil)

答案 2 :(得分:0)

您可以从导航堆栈中获取与第一个viewController类型相同的viewController,然后将其指定为vc4中的委托对象。

例如: 在vc4的viewDidLoad中,你可以这样做

Properties

我假设您的vc1,vc2,vc3等拥有自己的ViewController自定义类。

实现此方法的另一种方法是从self.navigationController?.viewControllers数组中获取第一个控制器,并将其设置为vc4中的委托对象。

for viewController in self.navigationController?.viewControllers{
if viewController.isKindOfClass(YourVC1ControllerType){
    self.delegate = viewController
}
}

,或者

//In viewDidLoad of vc4
 delegate = self.navigationController?.viewControllers.first as! HomeController