Search code examples
iosxcodexcode-storyboard

How to add an action on button touch up in iOS storyboard


I am new to iOS app development. I am going through the dev guides. My app has two views - one with a button and clicking that button launches a new view. I added a segue to launch the new view and was able to link it to the button. But its not clear to me what the exact action that launches the new view and how I can handle that action. I want to do some network operation before launching the new view and so want to handle that button click event (touch up). Can I get Xcode to generate a dummy handler function for that specific event?


Solution

  • Don't connect the segue to the button, connect the segue to the View Controller itself, then in the button's IBAction:

    - (IBAction)myButtonTapped:(id)sender {
        // If you need to do some other work prior to firing the segue, do it here.
    
        [self performSegueWithIdentifier:@"MySegue" sender:nil];
    }
    

    Then do your prep work in the prepareForSegue method:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
        NSString *identifier = segue.identifier;
    
        if ([identifier isEqualToString:@"MySegue"]) {
            // Do my stuff here
        }
    }
    

    I hardly ever connect segues to UIButtons, UITableCells, etc, I connect them to my VC and then in the action, call the segue. This gives you more control.