0
votes

I'm trying to send information between classes and 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?

1
If you aren't using a storyboard then you must be instantiating your view controller directly and then presenting it. Once you have instantiated the view controller you can simply set properties on it. - Paulw11
Sure, what would the code look like for setting the segue way Identifier using that process? - rob8989
You don't have a segue if you aren't using storyboard. You just use presentViewController:animated or similar - Paulw11
If i don't have a segue, how do I use protocol and delegates? From all the tutorials i've seen, you need to use prepareforsegue to set the delegate for the process to work. - rob8989
As I said, you will have the view controller reference already, so you don't need prepareForSegue. You can just set the delegate directly - Paulw11

1 Answers

0
votes

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:

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

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];