Search code examples
iosuisearchbardisplaycontrol

How to segue from a UISearchBarDisplayController result to a detailViewController


So, using storyboard you can create a segue from the UITableViewCell from the first tableViewController to a detailViewController.

Not too complicated, however, when a UISearchBarDisplayController is introduced into the storyboard mix, how can you segue the results cell to the detailViewController?

I am able to search without a problem, I followed this tutorial: http://clingingtoideas.blogspot.com/2010/02/uitableview-how-to-part-2-search.html

All I can do is select a row from the search, it turns blue and doesn't go to the detailViewController.

I have implemented the method prepareForSegue, which works for the non searched cells, but can't figure out this one.


Solution

  • Ok I think I got it, it seems like a bit of a hack but it works for my purposes:

    I am using storyboard: I have a UITableview controller with UISearchBarDisplayController directly on top of it. No code just drag and drop.

    From there, I followed this tutorial to get the search bar to search correctly http://clingingtoideas.blogspot.com/2010/02/uitableview-how-to-part-2-search.html

    However prepareForSegue: would only let me display a cell from the original array, not with the search array.

    So I used didSelectRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (savedSearchTerm) {
        searchRowSelected = indexPath.row;  //<-- the trick that worked
        [self performSegueWithIdentifier:@"ShowDetail" sender:self];
    }
    }
    

    searchRowSelected is an int variable that I declared at the top of the class.

    didSelectRowAtIndexPath: knew which row I was selecting, but prepareForSegue didn't. Thats why I needed that variable.

    This is how I used it in prepareForSegue:

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"ShowDetail"]) {
    
        dvc = [segue destinationViewController];
    
        NSIndexPath* path = [self.tableView indexPathForSelectedRow];
        int row = [path row];
    
        if (savedSearchTerm){   //set the detailViewController with the searched data cell 
            myDataClass* c = [searchResults objectAtIndex:searchRowSelected];
            dvc.myDataClass = c;
        }else{    //set the detailViewController with the original data cell
           myDataClass* c = [array objectAtIndex:row];
           dvc.myDataClass = c;
       }
    }
    }
    

    Also use this code to clean up savedSearchTerm

    -(void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller{
        [self setSavedSearchTerm:nil];
    }
    

    If anyone has a better solution I'm all ears :)