What is the correct usage of the UISearchBarDelegate showsSearchResultsButton attribute?

让人想犯罪 __ 提交于 2019-12-19 10:16:37

问题


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.



来源:https://stackoverflow.com/questions/5283058/what-is-the-correct-usage-of-the-uisearchbardelegate-showssearchresultsbutton-at

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!