What is the correct usage of the UISearchBarDelega

2020-03-29 02:59发布

问题:

I configure my search bar to show the results button, but the button only shows until the user enters a character. At that point, the "X" cancel button replaces it. So without entering characters, the search result set equals the entire data set. I'd like the results button to stay there so when the user has typed enough characters to get a smaller result set (like 5 or 6 rows), they can click the results button, my delegate will get called, and I can show just that result set.

UISearchBar * theSearchBar = [[UISearchBar alloc] 
                             initWithFrame:CGRectMake(0,0,700,40)];
theSearchBar.delegate = self;

theSearchBar.placeholder = @"What are you looking for?";
theSearchBar.showsCancelButton = NO;         // shows up after first char typed.
theSearchBar.showsSearchResultsButton = YES; // disappears just when I need it.

...further down in the VC... this method can only called when the search bar's input field is empty.

 - (void)searchBarResultsListButtonClicked:(UISearchBar *)searchBar {
         NSLog(@" searchBarResultsListButtonClicked for %@",searchBar); // 
    }

Advice, tutorials, sample code and justified dope-slaps welcome. TIA -Mike

回答1:

@Rayfleck, I think you should not worry about Search Results Button at all.

If what you need is to monitor user's input until they have entered enough characters for filtering:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ([searchText length]>5) {
        [self filterDataWithKeyword:searchText];
        [self.tableView reloadData];
    } else {
        [self resetFilter];
        [self.tableView reloadData];
    }
}


回答2:

Here is a partial answer that you can stick in viewDidLoad. It should hide the clear button, but it doesn't keep the results button visible. I'm not sure how the results button view logic is controlled behind the scenes.

for (id subview in mySearchBar.subviews) {
  if ([[subview class] isSubclassOfClass:[UITextField class]]) {
    [subview setClearButtonMode:UITextFieldViewModeNever];
    break;
  }
}

Since this approach uses all public APIs your app shouldn't get rejected. Although this approach might be prone to breaking further down the road if/when Apple decides to change the hierarchy of UISearchBar. All I'm doing is looking for the UITextField or subclass and setting its clearButtonMode.

Hope this helps.