[英]Cancel button on UISearchbar
我創建了帶有取消按鈕的UISearchbar
,但是當我單擊取消按鈕時,它不顯示數組,而只是關閉了鍵盤。
allItems
是NSArray
, displayItems
是NSMutableArray
-(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];
}
您確實應該為此使用兩個數組。 一個NSArray稱為原始數據,另一個NSMutableArray稱為filteredData。 它們在開始時都是相同的,並且在過濾時,您將從原始Data數組構建/重建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];
}
我還為ScrollView
( TableView
)添加了一個委托方法,以便當滾動開始時,鍵盤被關閉:
#pragma mark - ScrollView (UITableView) delegate methods
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
[mySearchBar resignFirstResponder];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.