Luke Luke - 3 years ago 69
iOS Question

Trigger a segue by hitting Search on keyboard

I have an app where I want a user to tap on a text field, type in their search query, and hit the keyboard's Return (or here, Search) button. Doing so should trigger a segue, and send some data in the

prepareForSegue
method to the next controller.

This method is currently being triggered by a UIButton, and it works fine, but I'd like the exact same thing to happen when hitting Search on the keyboard, so I can remove the button and streamline the process.

I've tried calling
[self prepareForSegue]
in the
textFieldShouldReturn
method (of the delegate) but it hasn't worked.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString: @"DisplaySearchResults"]) {
SearchResultsViewController *searchResultsViewController = [segue destinationViewController];
searchResultsViewController.searchQuery = _searchQuery;
}
}

Answer Source

You should call

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

in textFieldShouldReturn.

prepareForSegue will be called automatically after performSegueWithIdentifier.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download