在TableView中搜索,篩選出自己需要的內(nèi)容,需要用到iOS中的謂詞:NSPRedicate.謂詞的功能很想數(shù)據(jù)庫(kù)中的查詢語(yǔ)句,就是從數(shù)據(jù)集合中篩選出符合條件的對(duì)象,這讓我想起了在qt時(shí)遇到的正則表達(dá)式,不過當(dāng)時(shí)沒有好好學(xué).
方法步驟:
首先在表中加入搜索輸入框
UITextField *_textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 250, 30)]; _textField.borderStyle = UITextBorderStyleRoundedRect;//設(shè)置代理 _textField.delegate = self;//再次輸入時(shí)清空 _textField.clearsOnBeginEditing = YES;//設(shè)置return功能 _textField.returnKeyType = UIReturnKeyDone;//添加點(diǎn)擊事件 [_textField addTarget:self action:@selector(filter:) forControlEvents:UIControlEventEditingChanged]; self.navigationItem.titleView = _textField;
設(shè)置textfield的點(diǎn)擊事件
#pragma mark - UITextField Delegate- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES;}
重點(diǎn):textfield點(diǎn)擊事件
- (void)filter:(UITextField *)textField{ //當(dāng)輸入框中沒有輸入內(nèi)容時(shí),搜索結(jié)果與原數(shù)據(jù)不變 if ([textField.text length] == 0) { self.fontsArray = _data; [self.tableView reloadData]; return; } //設(shè)置謂詞內(nèi)容 NSString *regex = [NSString stringWithFormat:@"SELF LIKE[c]'%@*'", textField.text]; NSPredicate *predicate = [NSPredicate predicateWithFormat:regex]; //將篩選后的結(jié)果傳遞到元數(shù)據(jù)數(shù)組中 self.fontsArray = [_data filteredArrayUsingPredicate:predicate]; [self.tableView reloadData];}
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注