我正在创建一个实用的搜索栏过滤器,但遗憾的是它无效。我相信我错过了一个小细节。表视图工作正常而不是搜索栏过滤器。我没有使用故事板或xib文件进行此项目。
·H
UISearchBar *searchBar;
NSMutableArray * getterms;
@property (strong, nonatomic) NSMutableArray* allTableData;
@property (strong, nonatomic) NSMutableArray* filteredTableData;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, assign) bool isFiltered;
的.m
-(void)ViewDidLoad{
searchBar.delegate = self;
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(30, 10, 750, 31)];
searchBar.placeholder = @"Search"; //place holder
searchBar.backgroundColor = [UIColor whiteColor];
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searchBar.backgroundColor = [UIColor clearColor];
searchBar.keyboardType = UIKeyboardTypeDefault;
self.navigationItem.titleView = searchBar;
searchBar.layer.cornerRadius = 5;
searchBar.layer.masksToBounds = YES;
UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(10.0, 10.0, 1000.0, 200.0) style:UITableViewStylePlain];
self.tableView = tableView;
[self.view addSubview:tableView];
self.tableView.dataSource = self;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Food* food in allTableData)
{
NSRange nameRange = [food.name rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [food.description rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:food];
}
}
}
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MYCellIdentifier = @"MyCellIdentifier";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MYCellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MYCellIdentifier];
Food* food;
if(isFiltered)
food = [filteredTableData objectAtIndex:indexPath.row];
else
food = [allTableData objectAtIndex:indexPath.row];
cell.textLabel.text = food.name;
cell.detailTextLabel.text = food.description;
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
int rowCount;
if(self.isFiltered)
rowCount = filteredTableData.count;
else
rowCount = allTableData.count;
return rowCount;
}
答案 0 :(得分:0)
searchBar.delegate = self;
在searchBar分配之前。把它移到下面:
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(30, 10, 750, 31)];
searchBar.delegate = self;