iOS開發---簡單地搜索

iOS8以後咱們就能夠直接運用UISearchController的代理方法進行開發,不用再UIsearch和其餘的一下東西了,我就直接給你們上代碼吧ide

UISearchBarDelegate,UISearchResultsUpdating這兩個代理方法spa

viewdidload:代理

self.dataList=[NSMutableArray arrayWithCapacity:100];
    
    for (NSInteger i=0; i<100; i++) {
        [self.dataList addObject:[NSString stringWithFormat:@"%ld-FlyElephant",(long)i]];
    }
    ALog(@"-====%lu",(unsigned long)self.dataList.count);
  tableview =[[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableview.delegate =self;
    tableview.dataSource =self;
    [self.view addSubview:tableview];
  _search =[[UISearchController alloc]initWithSearchResultsController:nil];
    _search.searchResultsUpdater =self;
    _search.dimsBackgroundDuringPresentation = NO;
    _search.hidesNavigationBarDuringPresentation = NO;
    _search.searchBar.frame = CGRectMake(_search.searchBar.frame.origin.x, _search.searchBar.frame.origin.y, _search.searchBar.frame.size.width, 44);
//當作表的頭視圖 tableview.tableHeaderView
= _search.searchBar;

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//必定要判斷狀態
if (_search.active) { return [self.searchList count]; } else{ return [self.dataList count]; } } -(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *flag=@"cellFlag"; UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag]; if (cell==nil) { cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag]; } if (_search.active) { [cell.textLabel setText:self.searchList[indexPath.row]]; } else{ [cell.textLabel setText:self.dataList[indexPath.row]]; } return cell; } -(void)updateSearchResultsForSearchController:(UISearchController *)searchController { NSString *searchString =[_search.searchBar text];
//篩選語句 NSPredicate
*predicate =[ NSPredicate predicateWithFormat:@"SELF CONTAINS[c]%@",searchString]; if (self.searchList !=nil) { [self .searchList removeAllObjects]; } self.searchList = [NSMutableArray arrayWithArray:[self.dataList filteredArrayUsingPredicate:predicate]]; ALog(@"-==%ld",self.searchList.count); [tableview reloadData]; }
相關文章
相關標籤/搜索