博客> iOS - 模糊搜索 2
iOS - 模糊搜索 2
1小时前 评论:0 阅读:697 OS_JJ
ios 2 模糊搜索

 789197E767510C4D8BA0FAD6F83686A9.png  1C918AFB0DE8C3BD4B54DA3FA53F6AE7.png  23F88AF25F11F76455D5DD58E7BE184D.png

前言:简单版可查看 模糊搜索 1 博客

一、申明相关属性和代理

    <UITableViewDelegate>

    /// tableView 搜索页
    @property (nonatomic , strong) UIView *tableBGView;
    @property (nonatomic , strong) UITableView *tableSearchView;

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

二、创建导航栏视图 ,MSUHomeNavView

1.MSUHomeNavView.h 中的代码
    /// 返回按钮
    @property (nonatomic , strong) UIButton *backArrowBtn;
    /// 搜索框按钮
    @property (nonatomic , strong) UISearchBar *search;

2.MSUHomeNavView.m 中的代码

    - (instancetype)initWithFrame:(CGRect)frame showNavWithNumber:(NSInteger)number
    {
        if (self = [super initWithFrame:frame]) {
            switch (number) {
                  case 58:
            {
                /// 确认订单页面
                [self createbackNavViewWithTyper:number];
            }
                break;
                default:
                    break;
            }
        }
        return self;
    }

        - (void)createbackNavViewWithTyper:(NSInteger)typer{
            /// 取消按钮
            self.backArrowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [self addSubview:_backArrowBtn];
            [_backArrowBtn setTitle:@"取消" forState:UIControlStateNormal];
            _backArrowBtn.titleLabel.font = [UIFont systemFontOfSize:14];
            [_backArrowBtn setTitleColor:HEXCOLOR(0xffffff) forState:UIControlStateNormal];
            [_backArrowBtn makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.top).offset(0);
                make.left.equalTo(self.left).offset(14);
                make.width.equalTo(30);
                make.height.equalTo(40);
            }];

            /// 搜索框
        //    self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(40, 6, WIDTH-40-14, 28)];
        //    _search.placeholder =  @"搜索感兴趣的内容";
        //    _search.searchBarStyle = UISearchBarStyleMinimal;
        //    _search.backgroundImage = [self imageWithColor:WHITECOLOR size:_search.bounds.size];
        //    [self addSubview:_search];

            self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(48, 3, WIDTH-40-14, 34)];
            _search.placeholder =  @"搜索您的小伙伴";
            _search.backgroundImage = [self imageWithColor:WHITECOLOR size:_search.bounds.size];
            _search.layer.borderColor = NavColor.CGColor;
            _search.layer.borderWidth = 2;
            _search.layer.cornerRadius = 7;
            _search.clipsToBounds = YES;
            [self addSubview:_search];

        }

三、控制器中代码

    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.

        self.nav = [[MSUHomeNavView alloc] initWithFrame:NavRect showNavWithNumber:numer];
        [self.view addSubview:_nav];
        _nav.search.delegate = self;

         [self createTableView];
    }

    /* 搜索列表视图 */
    - (void)createTableView{
        self.tableBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, WIDTH, HEIGHT-60)];
        _tableBGView.backgroundColor = HEXCOLOR(0xf4f4f4);
        _tableBGView.hidden = YES;
        [self.view addSubview:_tableBGView];

        // 列表初始化
        self.tableSearchView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10,WIDTH ,HEIGHT-60-10) style:UITableViewStylePlain];
        _tableSearchView.delegate = self;
        _tableSearchView.dataSource = self;
        _tableSearchView.separatorStyle = UITableViewCellSelectionStyleNone;
        //    _tableView.bounces = NO;
        _tableSearchView.showsVerticalScrollIndicator = NO;
        _tableSearchView.rowHeight = 36;
        [_tableBGView addSubview:_tableSearchView];
    }

    #pragma mark - 代理
    /* searchBar 代理方法 */
    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
        // 请求搜索数据 AFN请求后台匹配数据 返回格式是数组格式
        //    NSLog(@"参数%@",self.navView.search.text);
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        if (!token) {
            token = @"";
        }
        NSDictionary *dic = @{@"token":token,@"keyword":_nav.search.text,@"type":@"1"};
        __weak typeof(self) weakSelf = self;
        [[MSUAFNRequest sharedInstance] postRequestWithURL:@"http://api.showXX100.com/index/compare-res" parameters:dic withBlock:^(id obj, NSError *error) {
            if (obj) {
                weakSelf.dataList = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableLeaves error:nil];
                if (!error) {
                    NSLog(@"访问成功%@",_dataList);
                    // 如果搜索内容不为空,显示 tableBGView
                    if (searchText.length > 0) {
                        weakSelf.tableBGView.hidden = NO;

                        // 如果搜索结果不为空,筛选过滤数据
                        if (weakSelf.dataList.count > 0) {
                            weakSelf.inputString = searchText;
                            NSPredicate *preicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[c] %@", searchText];
                            if (weakSelf.searchList) {
                                [weakSelf.searchList removeAllObjects];
                            }
                            //过滤数据
                            weakSelf.searchList = [NSMutableArray arrayWithArray:[_dataList filteredArrayUsingPredicate:preicate]];

                        } else{
                            // 清空历史搜索
                            if (weakSelf.searchList.count > 0) {
                                [weakSelf.searchList removeAllObjects];
                            }
                        }
                        //刷新表格
                        [weakSelf.tableSearchView reloadData];
                    }else{
                        weakSelf.tableBGView.hidden = YES;
                    }
                }else{
                    NSLog(@"访问报错%@",error);
                }
            } else{
                [MSUHUD showFileWithString:@"服务器请求为空"];
            }

        }];

        // 去除搜索框所有文字 或者点击叉叉按钮
        if (!searchText || searchText.length <= 0) {
            _tableBGView.hidden = YES;
        }
    }

    /* 搜索按钮点击 */
    - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
        [self searchDidSure];
    }

    /* 确定搜索事件 */
    - (void)searchDidSure{
        _tableBGView.hidden = YES;
        [_nav.search resignFirstResponder];

        // 请求数据 接口可忽视
        __weak typeof(self) weakSelf = self;
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        if (!token) {
            token = @"";
        }
        NSDictionary *dic = @{@"keyword":self.nav.search.text,@"token":token};
        [[MSUAFNRequest sharedInstance] postRequestWithURL:@"http://api.showbuy100.com/index/search-following" parameters:dic withBlock:^(id obj, NSError *error) {
            if (obj) {
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:obj options:NSJSONReadingMutableLeaves error:nil];
                if (!error) {
                    NSLog(@"访问成功%@",jsonDict);
                    if ([jsonDict[@"code"] isEqualToNumber:[NSNumber numberWithInteger:1]]) {
                        __strong typeof(weakSelf) strongSelf = weakSelf;

                        NSDictionary *dic = jsonDict[@"data"];
                        strongSelf.hidesBottomBarWhenPushed = YES;
                        MSUMessageChatController *chat = [[MSUMessageChatController alloc] initWithConversationChatter:dic[@"mobile"] conversationType:EMConversationTypeChat];
                        chat.sellerNickName = dic[@"nickname"];
                        chat.sellerIconUrl = dic[@"avatar"];
                        chat.userId = dic[@"id"];
                        chat.myselfIcon = dic[@"my_avatar"];
                        [strongSelf.navigationController pushViewController:chat animated:YES];
                    }

                }else{
                    NSLog(@"访问报错%@",error);
                }
            } else{
                [MSUHUD showFileWithString:@"服务器请求为空"];
            }

        }];
    }

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        if (self.inputString && self.inputString.length > 0) {
                return [self.searchList count];
            }else{
                return [self.dataList count];
            }
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
      static NSString *flag = @"cell";
            MSUSearchTableCell *cell=[tableView dequeueReusableCellWithIdentifier:flag];
            if (cell == nil) {
                cell = [[MSUSearchTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:flag historyNum:0];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            if (self.inputString && self.inputString.length > 0) {
                [UIView animateWithDuration:0.25 animations:^{
                } completion:^(BOOL finished) {
                    _tableBGView.hidden = NO;
                    // 将带属性的字符串添加到cell.textLabel上.
                    if (self.searchList && self.searchList.count>0) {
                        [cell.searLab setAttributedText:[MSUStringTools makeKeyWordAttributedWithSubText:self.inputString inOrigiText:self.searchList[indexPath.row] font:14 color:HEXCOLOR(0xff7e00)]];
                    }
                }];
            }
            else{
                _tableBGView.hidden = YES;
            }
            return cell;
    }

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
           self.nav.search.text = self.searchList[indexPath.row];
            [self searchDidSure];
      }
收藏
0
sina weixin mail 回到顶部