UISearchbar上的取消按钮

时间:2012-10-30 14:59:41

标签: ios uisearchbar

我创建了一个带有取消按钮的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];
}

1 个答案:

答案 0 :(得分:1)

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

-(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]; 
}

我还为ScrollViewTableView)添加了一个委托方法,这样当滚动开始时,键盘就会被解雇:

#pragma mark - ScrollView (UITableView) delegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [mySearchBar resignFirstResponder];
}