iOS中搜索框EVNCustomSearchBar使用小结

  最近在项目开发中用到了搜索框,之前都是用的系统的searchbar,现有项目中用的是EVNCustomSearchBar,我试了一下还挺方便,下面说一下具体的用法。

  第一步:引入添加相关的委托代理EVNCustomSearchBarDelegate懒加载初始化对象

  

if (!_searchBar) {

        _searchBar = [[EVNCustomSearchBar alloc] initWithFrame:CGRectMake(16, 0, K_CC_SCREEN_WIDTH-32, 44)];

        _searchBar.backgroundColor = K_CC_COLOR_STRING(@"#F5F5F5");

        _searchBar.textColor = K_CC_COLOR_STRING(@"#999999");

        _searchBar.textFieldColor = [UIColor clearColor];

        _searchBar.iconImage = K_CC_IMAGE(@"newhome_search");

        _searchBar.iconAlign = EVNCustomSearchBarIconAlignCenter;

        [_searchBar setPlaceholder:K_CC_LOCAL_STR(@"home.search")];// 搜索框的占位符

        _searchBar.placeholderColor = K_CC_COLOR_STRING(@"#999999");

        _searchBar.delegate = self; //设置代理

        _searchBar.isHiddenCancelButton = YES;

        _searchBar.tintColor = K_CC_COLOR_STRING(@"#999999");

        [_searchBar sizeToFit];

        

    }

    return _searchBar;

  第二步:添加到相应的view上

  

UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, K_CC_SCREEN_WIDTH, 44)];

    headerView.backgroundColor = [UIColor clearColor];

    [headerView addSubview:self.searchBar];

    self.distributeTable.tableHeaderView = headerView;

  第三步:添加相关的搜索代理逻辑处理

  

#pragma mark - EVNCustomSearchBarDelegate -

- (void)searchBar:(EVNCustomSearchBar *)searchBar textDidChange:(NSString *)searchText {

    if (searchText.length > 0) {

        // 根据模型属性搜索结果

        self.searchList=[NSMutableArray arrayWithArray:[[NDSearchTool tool] searchWithFieldArray:@[@"username"] inputString:searchText inArray:self.dataAddressList]];

        self.isSearch = YES;

        

    }else{

        self.isSearch = NO;

        self.currentSeasSearchItem=-1;

        //清空搜索内容Id

        [self.searchList removeAllObjects];

    }

    [self.distributeTable reloadData];

}

- (NSArray *)searchWithFieldArray:(NSArray *)fieldArray

                      inputString:(NSString *)inputString

                          inArray:(NSArray *)array

{

    if (![array count] || ![fieldArray count])

    {

        return nil;

    }

    

    NSPredicate *scopePredicate;

    NSMutableArray *backArray = [NSMutableArray array];

    

    for (NSString *fieldString in fieldArray)

    {

        NSArray *tempArray;

        scopePredicate = [NSPredicate predicateWithFormat:@"SELF.%@ contains[c] %@", fieldString, inputString];

        tempArray = [array filteredArrayUsingPredicate:scopePredicate];

        

        for (NSObject *object in tempArray)

        {

            if (![backArray containsObject:object])

            {

                [backArray nd_addObj:object];

            }

        }

    }

    

    return backArray;

}

  完成这些就可以实现动态的模糊搜索,大功告成。

posted @ 2021-04-21 16:50  奔跑的小蚂蚁9538  阅读(65)  评论(0编辑  收藏  举报