IOS7, Segue and storyboards - How to create without a button?
Asked Answered
L

1

70

I currently have a login View and an Application view, I have successfully implemented validation on the login view and I need to programmatically shift to the application view on successful validation.

I understand I can add a segue to the login button and then call it programmatically like so...

[self performSegueWithIdentifier:@"LoginSegue" sender:sender];

But this will obviously be triggered whenever the button is clicked (As the segue was created attached to the button). I've just read that I should create a button (And hide it) and then make a programmatic call to the segue - this seems a bit 'wrong'.

How can a create a segue that isn't attached to any particular UI event?

Levitt answered 18/1, 2014 at 14:34 Comment(0)
S
148

Delete the current segue.

Attach the segue from the origin view controller to the destination (and then name it).

Now, your button press method should look something like this:

Objective-C:

- (IBAction)validateLogin:(id)sender {
    // validate login
    if (validLogin) {
        [self performSegueWithIdentifier:@"mySegue" sender:sender];
    }
}

Swift:

@IBAction func validateLogin(sender: UIButton) {
    // validate login
    if validLogin {
        self.performSegueWithIdentifier("mySegue", sender:sender)
    }
}

The key here is that the origin view controller should be the one you're dragging from to create the segue, not the button or any other UI element.

enter image description here

Personally, I hook ALL of my segues up this way, even the ones that should trigger on simple button pushes without any validation or logic behind them. It's easy enough to call it from the button's method.

And, I usually declare all of my segue names as constant strings somewhere in the project.

Sailmaker answered 18/1, 2014 at 14:41 Comment(4)
No problem. Personally, I hook ALL of my segues up this way, even the ones that should trigger on simple button pushes without any validation or logic behind them. It's easy enough to call it from the button's method.Sailmaker
I did not know you could do this lol, Thanks!!! ... I've been creating hidden/invisible buttons in order to create segues; which I would then name and trigger when necessary :SAery
Just a note, if you have storyboard references (for organisational purposes) you can connect a segue by going to the object library and dragging a 'storyboard reference' object to your storyboard. Then connect the segue as explained above...Heraclea
I also had to manually give the segue an identifier. In Xcode 12 I had to select the segue in the graphical storyboard, and then click the icon that looks like 3 sliders in the attribute panel. That is where you can enter an identifier for it. Otherwise you get an error that there is no segue.Septum

© 2022 - 2024 — McMap. All rights reserved.