4
votes

I'm using the UISearchBar of a UISearchController in the header of a UITableView. My searching works OK in that when I enter some text in the search bar's field, all the relevant methods are called and the table view shows the correct search results as expected.

The problem comes when I want to tap on one of the results to do something with it. As soon as I tap on one of the table view cells, the field in the search bar becomes empty. Since the search text is now empty, the search results are updated and the table view reloads with zero results. So the tap on the table cell does nothing, because the table cell no longer exists.

I can work around most of this problem by updating my updateSearchResultsForSearchController: method to not update the search results when the search string is empty. And this works fine. But in any case, I do still want the search text to remain in the search field, and this is the crux of my question...

Why is my search text disappearing from the search field, and how can I prevent the search field from becoming empty when I tap elsewhere?

Here's how I set up the search bar and search controller:

- (void)viewDidLoad {
    [super viewDidLoad];

    searcher = [[UISearchController alloc] initWithSearchResultsController:nil];
    searcher.searchResultsUpdater = self;
    searcher.delegate = self;
    searcher.definesPresentationContext = YES;
    resultsTable.tableHeaderView = searcher.searchBar;

EDIT: I notice that the table view cells are dimmed while the search bar has focus. So I think that the search controller is capturing all touches and perhaps handles them as 'cancel' actions. If so, how do I stop it cancelling in this way?

1
Take a look at developer.apple.com/reference/uikit/uisearchcontroller/… >"If you use the same view controller to display the searchable content and search results, it is recommended that you set this property to false. The default value of this property is true."Mike Sand
Yes, you are correct - that has solved my issue. I found it myself at about the same time you posted. I feel a bit silly. Anyhow, I've posted it as an answer now, in case it helps anyone else later.Son of a Beach

1 Answers

14
votes

Figured it out. I needed to add:

searcher.obscuresBackgroundDuringPresentation = NO;