博客> iOS-搜索框 模糊查询 (UISearchController 和 UISearchBar)
iOS-搜索框 模糊查询 (UISearchController 和 UISearchBar)
2017-07-22 20:10 评论:0 阅读:187 OS_JJ
ios 搜索框 模糊查询 (UISearchController UISearchBar)

一、模糊查询

第一种方法:UISearchController

    1.代理协议 和 属性    相关

        代理协议:
        UITableViewDelegate,UITableViewDataSource,UISearchControllerDelegate,UISearchResultsUpdating

        属性:
        //tableView
        @property (strong, nonatomic)  UITableView *tableView;
        //searchController
        @property (strong, nonatomic)  UISearchController *searchController;
        //数据源
        @property (strong,nonatomic) NSMutableArray  *dataList;
        @property (strong,nonatomic) NSMutableArray  *searchList;

    2.数组初始化和创建tableview searchcontroller

        - (void)viewDidLoad {
            [super viewDidLoad];

            _dataList = [NSMutableArray array];
            _searchList = [NSMutableArray array];

            self.dataList=[NSMutableArray arrayWithCapacity:100];

            //产生100个“数字+三个随机字母”
            for (NSInteger i=0; i<100; i++) {
                [self.dataList addObject:[NSString stringWithFormat:@"%ld%@",(long)i,[self shuffledAlphabet]]];
            }

            //创建UISearchController
            self.searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
            //设置代理
            _searchController.delegate = self;
            _searchController.searchResultsUpdater= self;
            //设置UISearchController的显示属性,以下3个属性默认为YES
            //搜索时,背景变暗色
            _searchController.dimsBackgroundDuringPresentation = NO;
            //搜索时,背景变模糊
            _searchController.obscuresBackgroundDuringPresentation = NO;
            //隐藏导航栏
            _searchController.hidesNavigationBarDuringPresentation = NO;
            _searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
            _searchController.searchBar.searchBarStyle = UISearchBarStyleMinimal;
            _searchController.searchBar.backgroundColor = [UIColor whiteColor];

            /// tableview
            _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20,WIDTH ,HEIGHT-64) style:UITableViewStylePlain];
            _tableView.delegate = self;
            _tableView.dataSource = self;
            _tableView.separatorStyle = UITableViewCellSelectionStyleNone;
        //    _tableView.bounces = NO;
            _tableView.showsVerticalScrollIndicator = NO;
            [self.view addSubview:_tableView];
            _tableView.tableHeaderView = _searchController.searchBar;

                }

    3.假数据随机方法 和 相关代理

        //产生3个随机字母
        - (NSString *)shuffledAlphabet {

            NSMutableArray * shuffledAlphabet = [NSMutableArray arrayWithArray:@[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"]];

            NSString *strTest = [[NSString alloc]init];
            for (int i=0; i<3; i++) {
                int x = arc4random() % 25;
                strTest = [NSString stringWithFormat:@"%@%@",strTest,shuffledAlphabet[x]];
            }

            return strTest;

        }

        //设置区域的行数
        -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
            if (self.searchController.active) {
                return [self.searchList count];
            }else{
                return [self.dataList count];
            }
        }

        //返回单元格内容
        -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
            static NSString *flag=@"cell";
            UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
            if (cell==nil) {
                cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
            }
            if (self.searchController.active) {
                [cell.textLabel setText:self.searchList[indexPath.row]];
            }
            else{
                [cell.textLabel setText:self.dataList[indexPath.row]];
            }
            return cell;
        }

        #pragma mark - UISearchControllerDelegate代理

        //测试UISearchController的执行过程

        - (void)willPresentSearchController:(UISearchController *)searchController
        {
            NSLog(@"willPresentSearchController");
        }

        - (void)didPresentSearchController:(UISearchController *)searchController
        {
            NSLog(@"didPresentSearchController");
        }

        - (void)willDismissSearchController:(UISearchController *)searchController
        {
            NSLog(@"willDismissSearchController");
        }

        - (void)didDismissSearchController:(UISearchController *)searchController
        {
            NSLog(@"didDismissSearchController");
        }

        - (void)presentSearchController:(UISearchController *)searchController
        {
            NSLog(@"presentSearchController");
        }

        -(void)updateSearchResultsForSearchController:(UISearchController *)searchController {

            // 修改UISearchBar右侧的取消按钮文字颜色及背景图片
            searchController.searchBar.showsCancelButton = YES;
            for (id searchbuttons in [[searchController.searchBar subviews][0] subviews]) //只需在此处修改即可

                if ([searchbuttons isKindOfClass:[UIButton class]]) {
                    UIButton *cancelButton = (UIButton*)searchbuttons;
                    // 修改文字颜色
                    [cancelButton setTitle:@"返回"forState:UIControlStateNormal];
                    [cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                }

            NSLog(@"updateSearchResultsForSearchController");
            NSString *searchString = [self.searchController.searchBar text];
            NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchString];
            if (self.searchList!= nil) {
                [self.searchList removeAllObjects];
            }
            //过滤数据
            self.searchList= [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:preicate]];
            //刷新表格
            [self.tableView reloadData];
        }

第二种方法:UISearchBar

        1.代理和属性

            UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate

            //tableView
            @property (strong, nonatomic)  UITableView *tableView;
            //searchBar
            @property (nonatomic , strong) UISearchBar *search;
            @property (nonatomic , strong) UIButton *searchCancleBtn;

            //数据源
            @property (strong,nonatomic) NSMutableArray  *dataList;
            @property (strong,nonatomic) NSMutableArray  *searchList;

        2.初始化

            /** 搜索框背景图片的封装方法 */
            - (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
                CGRect recte = CGRectMake(0, 0, size.width, size.height);
                UIGraphicsBeginImageContext(recte.size);
                CGContextRef context = UIGraphicsGetCurrentContext();

                CGContextSetFillColorWithColor(context, [color CGColor]);
                CGContextFillRect(context, recte);

                UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
                UIGraphicsEndImageContext();

                return image;
            }

            - (void)viewDidLoad {
                [super viewDidLoad];

                _dataList = [NSMutableArray array];
                _searchList = [NSMutableArray array];

                self.dataList=[NSMutableArray arrayWithCapacity:100];

                //产生100个“数字+三个随机字母”
                for (NSInteger i=0; i<100 xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed i=0; xss=removed xss=removed> 0) {
                    return [self.searchList count];
                }else{
                    return [self.dataList count];
                }
            }

            //返回单元格内容
            -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
                static NSString *flag=@"cell";
                UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
                if (cell==nil) {
                    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag];
                    cell.backgroundColor = [UIColor yellowColor];
                }
                if (self.inputString && self.inputString.length > 0) {
                    [cell.textLabel setText:self.searchList[indexPath.row]];
                }
                else{
                    [cell.textLabel setText:self.dataList[indexPath.row]];
                }
                return cell;
            }

二、UISearchBar

第一种方式

        1.创建UISearchBar

            UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 72, WIDTH, HEIGHT/16+10)];
            bgView.backgroundColor = WHITECOLOR;
            [self.view addSubview:bgView];

            UISearchBar *search = [[UISearchBar alloc]initWithFrame:CGRectMake(5, 5, WIDTH-10, HEIGHT/16)];
            search.placeholder =  @"搜索朋友";
            search.backgroundColor = REDCOLOR;
            search.backgroundImage = [self imageWithColor:WHITECOLOR size:search.bounds.size];
            search.layer.borderColor = CAOGREENCOLOR.CGColor;
            search.layer.borderWidth = 2;
            search.layer.cornerRadius = 3;
            search.clipsToBounds = YES;
            [bgView addSubview:search];

        2.搜索框表象封装方法

        /** 搜索框背景图片的封装方法 */
        - (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
            CGRect recte = CGRectMake(0, 0, size.width, size.height);
            UIGraphicsBeginImageContext(recte.size);
            CGContextRef context = UIGraphicsGetCurrentContext();

            CGContextSetFillColorWithColor(context, [color CGColor]);
            CGContextFillRect(context, recte);

            UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            return image;
        }

        - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
            self.inputString = searchText;
            NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchText];
            if (self.searchList!= nil) {
                [self.searchList removeAllObjects];
            }
            //过滤数据
            self.searchList = [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:preicate]];

            //刷新表格
            [self.tableView reloadData];

        }

第二种方式

        //搜索框
        self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(100, 30, WIDTH-100-100, 30)];
      self.search.placeholder =  @"请搜索输入";
      self.search.searchBarStyle = UISearchBarStyleMinimal;
      self.search.delegate = self;
      self.navigationItem.titleView = self.search;
      //    [search setBackgroundImage:[[UIImage alloc] init]];
      //    [search setImage:[UIImage imageNamed:@"error.png"] forSearchBarIcon:UISearchBarIconClear     state:UIControlStateNormal];
收藏
1
sina weixin mail 回到顶部