简体   繁体   English

如何以编程方式创建与协议和代理一起使用的segue(swift 3 xcode)

[英]how to programmatically create segue for use with Protocol & Delegate (swift 3 xcode)

I'm trying to send information between classes and ViewControllers. 我试图在类和ViewControllers之间发送信息。 I've looked at protocols and delegates as a way of achieving this but, it seems I need a segue between the viewcontrollers to access the delegate. 我已经看过协议和委托作为实现此目的的一种方法,但是看来我需要在视图控制器之间进行访问才能访问委托。 I'm not using a storyboard so I can't create a segue, as such I have two questions: 我没有使用情节提要,所以无法创建主题,因此我有两个问题:

  1. Can I create a segue programmatically between two view controllers? 我可以在两个视图控制器之间以编程方式创建序列吗? If so, how do I do that? 如果是这样,我该怎么做?

  2. Additionally, if I have two classes in the same viewController and I would like to access data from one to the other, is using protocols and delegates the best method to achieve this or is NSNotificationcenter a better option? 另外,如果我在同一个viewController中有两个类,并且想从一个类访问另一个类的数据,是否正在使用协议并委托实现此目的的最佳方法?还是NSNotificationcenter是更好的选择?

If you need set a delegate between another class if the segue is not used, You can create an instance of the secondViewController and with this instance you call call delegate refer this Code: 如果您需要在不使用segue的情况下在另一个类之间设置委托,则可以创建secondViewController的实例,并使用此实例调用调用委托,请参考以下代码:

In Swift 斯威夫特

if you are Presenting it modely, 如果您要适时呈现,

let VC = SecondViewContoller()
    VC.delegate = self
    present(VC, animated: true, completion: nil)

if you are pushing, 如果你在推,

let VC = MeaasgesController()
    VC.delegate = self
    self.navigationController?.pushViewController(VC, animated: true)

In Objective-C Objective-C中

if you are Presenting it modely, 如果您要适时呈现,

SecondViewContoller *VC = [[SecondViewContoller alloc] init];
VC.delegate = self;
[self presentViewController:VC animated:YES completion:nil];

if you are pushing, 如果你在推,

SecondViewContoller *VC = [[SecondViewContoller alloc] init];
VC.delegate = self;
[self.navigationController pushViewController:VC animated:YES];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM