我想在表视图中添加简单的搜索栏。程序运行时没有错误..但是当我尝试在搜索栏程序中添加文本时终止...以下是我的代码: -
@interface RootViewController:UITableViewController { NSArray * list;
IBOutlet UISearchBar *searchBar;
NSMutableArray *searchresult;
BOOL isSearchon;
BOOL canSelectRow;
} @property(nonatomic,retain)NSArray * list; @property(nonatomic,retain)IBOutlet UISearchBar * searchBar; - (无效)doneSearching:(ID)发送者;
- (无效)searchlist;
@end
//在.m
@implementation RootViewController
@synthesize list,searchBar;
- (无效)doneSearching:(ID)发送方
{ isSearchon = NO;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
self.navigationItem.rightBarButtonItem=nil;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}
- (无效)searchlist
{NSString * searchText = searchBar.text;
[searchresult removeAllObjects];
for(NSString *str in list)
{
NSRange titleResultsRange=[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchresult addObject:str];
}
}
(void)searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchlist]; }
(void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if([searchText length]> 0)
{isSearchon = YES;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
[self searchlist];}
否则{ isSearchon = NO;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
}
[self.tableView reloadData];
}
(void)viewDidLoad { [super viewDidLoad];
list = [[NSArray alloc] initWithObjects:@“rohan”,@“vidhya”,@“kavita”,@“pushkar”,nil];
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeYes;
searchresult = [[NSMutableArray alloc] init];
isSearchon = NO;
canSelectRow = YES;
self.navigationItem.title = @“姓名”;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{ isSearchon = YES;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneSearching:)]autorelease];
}
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
返回1; }
//自定义表视图中的行数。 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 如果(isSearchon){ return [searchresult count];}
else{
return [list count];}
}
//自定义表格视图单元格的外观。 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if(isSearchon)
{
cell.text=[searchresult objectAtIndex:indexPath.row];}
else{
cell.text=[list objectAtIndex:indexPath.row];}
// Configure the cell.
return cell;
}
@end
答案 0 :(得分:1)
我已经在我的问题中编辑了我的代码......它工作得很好......任何愿意在Iphone的tableview中使用搜索栏的AnyOne都可以参考代码。