1

UISearchbar用取消按钮创建了一个,但是当我单击取消按钮时,它不显示数组,它只是关闭键盘。

allItemsNSArraydisplayItemsNSMutableArray

-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar{
[displayItems addObject:allItems];
[searchBar resignFirstResponder];
 }


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

if ([searchText length] == 0) {
    [displayItems removeAllObjects];
    [displayItems addObjectsFromArray:allItems];

} else {

    [displayItems removeAllObjects];
    for (NSString * string in allItems ){
        NSRange r =[string rangeOfString:searchText options:NSCaseInsensitiveSearch];

        if (r.location != NSNotFound){
            [displayItems addObject:string];
        }
    }

    [tableView reloadData];

} 

 }


       - (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellAccessoryDisclosureIndicator;
}

 -(void)searchBarCancelButtonClicked:(UISearchBar *)asearchBar{
[displayItems removeAllObjects];
[displayItems addObjectsFromArray:allItems];
[searchBar resignFirstResponder];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)asearchBar{
[searchBar resignFirstResponder];
}
4

1 回答 1

1

你真的应该为此使用两个数组。一个是 NSArray,叫做 originalData,另一个是 NSMutableArray,叫做filteredData。这些在开始时都是相同的,在过滤时,您将从 originalData 数组构建/重建过滤数据数组。这是一个粗略的例子:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{

    if ([searchText length]) {
        [displayItems removeAllObjects];
        for (NSString * string in allItems ){
            NSRange r =[string rangeOfString:searchText options:NSCaseInsensitiveSearch];

            if (r.location != NSNotFound){
                [displayItems addObject:string];
            }

        [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
        }
    } 
}



-(void)searchBarCancelButtonClicked:(UISearchBar *)asearchBar{
    [searchBar resignFirstResponder];
    self.displayItems = [[NSMutableArray alloc] initWithArray:allItems];
    [tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 
}

ScrollView我还为( )添加了一个委托方法,TableView以便在滚动开始时,键盘被关闭:

#pragma mark - ScrollView (UITableView) delegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [mySearchBar resignFirstResponder];
}
于 2012-10-30T15:33:25.090 回答