美文网首页
IOS搜索条

IOS搜索条

作者: J_mine | 来源:发表于2017-11-01 09:07 被阅读0次

    viewController.m

    #import "ViewController.h"
    #import "TableViewCell.h"
    
    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate,UISearchResultsUpdating>
    {
        UITableView *table;
        
        UISearchController *sear;
        
        NSMutableArray *arr;
        
        NSArray *arr2;
    }
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // 创建表格
        table=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height -20)];
        
        [table registerClass:[TableViewCell class] forCellReuseIdentifier:@"Mycell"];
        
        //设置代理
        table.dataSource=self;
        table.delegate=self;
        
        //添加到视图
        [self.view addSubview:table];
        
        //创建搜索条
        sear=[[UISearchController alloc]initWithSearchResultsController:nil];
        
        sear.searchBar.placeholder=@"搜索";
        sear.searchResultsUpdater=self;
        
        
        table.tableHeaderView=sear.searchBar;
        
        //创建数据
        arr=[NSMutableArray arrayWithObjects:@"one",@"two",@"three", nil];
        
        
    }
    - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
    {
        NSPredicate *pre=[NSPredicate predicateWithFormat:@"self contains %@",sear.searchBar.text];
        arr2=[arr filteredArrayUsingPredicate:pre];
        [table reloadData];
    }
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        if(sear.isActive==YES)
        {
            return arr2.count;
        }
        return arr.count;
    }
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"Mycell" forIndexPath:indexPath];
        
        if(sear.isActive==YES)
        {
            cell.textLabel.text=arr2[indexPath.row];
        }
        else
        {
            cell.textLabel.text=arr[indexPath.row];
        }
        
        return cell;
    }
    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        return 50;
    }
    
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    
    

    相关文章

      网友评论

          本文标题:IOS搜索条

          本文链接:https://www.haomeiwen.com/subject/grdwpxtx.html