1

我正在务实地创建一个搜索栏过滤器,但遗憾的是它不起作用。我相信我遗漏了一个小细节。表格视图工作正常,只是搜索栏过滤器没有。我没有为这个项目使用故事板或 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;
 }
4

1 回答 1

0
searchBar.delegate = self; 

是在 searchBar 分配之前。将其移至下方:

searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(30, 10, 750, 31)];
searchBar.delegate = self;
于 2013-04-08T20:12:39.637 回答