iOS - 模糊搜尋 2

weixin_33890499發表於2017-10-27
789197E767510C4D8BA0FAD6F83686A9.png

1C918AFB0DE8C3BD4B54DA3FA53F6AE7.png

23F88AF25F11F76455D5DD58E7BE184D.png

前言:簡單版可檢視 模糊搜尋 1 部落格

一、申明相關屬性和代理

    <UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,UISearchBarDelegate>

    /// 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];
      }

相關文章