Doug Smith
Doug Smith

Reputation: 29316

How to tap on a UIButton in a UITableViewCell and transition to a new view controller, passing it information?

I have a bunch of UITableViewCells that each have a UIButton in them. The UIButton is to a link, and that's what the UIButton's text is.

When I tap on the button in the cell I want to transition to a view controller with a WKWebView in it showing the link.

How would I design this flow? I can detect the tap and find out what cell the button tapped belongs to, and then as a result find the link, but then how do I transition to the new view controller? If I call performSegueWithIdentifier I can't pass any information, can I?

Upvotes: 0

Views: 130

Answers (2)

Duncan C
Duncan C

Reputation: 131408

Expanding on Morgan's answer:

In the code that responds to a user tapping on a row, save the index of the row to an instance variable. Then invoke your segue using performSegueWithIdentifier.

Your prepareForSegue will then be called. In prepareForSegue, use the index of the selected item to look up the data you want to pass to the destination view controller, cast the destination view controller to the correct type, and pass the data to a property of the destination.

If you need to pass data back from the destination to the source view controller, set a delegate in the destination and use delegate methods to pass the data back.

Upvotes: 0

Morgan Chen
Morgan Chen

Reputation: 1217

You can pass information in prepareForSegue: sender:.

-(void)prepareForSegue:(UIStoryBoardSegue *)segue sender:(id)sender {
    if([segue.identifier isEqualToString:@"MyIdentifier"]) {

        // get destination
        CustomViewController *destination = (CustomViewController *)[segue destinationViewController];

        // pass information of some kind
        destination.exampleProperty = @"Hello World";
    }
}

The method above will be called following any calls to performSegueWithIdentifier.

Upvotes: 1

Related Questions