当在iPhone中单击键盘上的搜索按钮时,搜索栏中的文本消失

时间:2014-05-31 13:00:32

标签: ios iphone searchbar

在iPhone的搜索栏中输入文字后,当在键盘上单击搜索按钮时,文本消失。我添加了<UISearchDisplayDelegate, UISearchBarDelegate>BOOL isSearching;

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    isSearching = YES;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
     NSLog(@"Text change - %d",isSearching);
     NSString *str = searchBar.text;
     self.searchDisplayController.searchBar.text = str;
     //Remove all objects first.
     [filteredArray removeAllObjects];

     if([searchText length] != 0) {
         isSearching = YES;
         [self searchTableList];
     }
     else {
         isSearching = NO;
     }
     [self.tableView1 reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
  NSLog(@"Cancel clicked");
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
   [self searchTableList];
   [searchBar resignFirstResponder];
}
- (void)searchTableList {
    searchString = searchBar.text;

    for (NSString *tempStr in tableData) {
        NSComparisonResult result = [tempStr compare:searchString options:   (NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
        if (result == NSOrderedSame) {
            [filteredArray addObject:tempStr];
        }
    }
}

2 个答案:

答案 0 :(得分:2)

Swift 4.0:

我遇到了同样的问题,但是我通过定义UISearchBarDelegate方法(即searchBarTextDidEndEditing

)解决了
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {

}

无需在方法中编写任何代码。 希望这个答案对您有帮助。

答案 1 :(得分:0)

我对UISearchController有同样的问题 我阻止搜索控制器清除将其存储在字符串中的文本,稍后,在停用控制器后,将存储的文本分配给搜索栏。

目标C:

-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *text = searchBar.text;
    [self.searchController setActive:NO animated:YES];
    self.searchController.searchBar.text = text;
}

Swift 2.X:

func searchBarSearchButtonClicked(searchBar: UISearchBar) {
    let text = searchBar.text
    searchController.active = false
    searchController.searchBar.text = text
}

希望它有所帮助。