首页 > 学院 > 开发设计 > 正文

在TableVIew中搜索筛选:谓词

2019-11-14 18:17:56
字体:
来源:转载
供稿:网友

在TableView中搜索,筛选出自己需要的内容,需要用到iOS中的谓词:NSPRedicate.谓词的功能很想数据库中的查询语句,就是从数据集合中筛选出符合条件的对象,这让我想起了在qt时遇到的正则表达式,不过当时没有好好学.

 

方法步骤:

首先在表中加入搜索输入框

UITextField *_textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 250, 30)];    _textField.borderStyle = UITextBorderStyleRoundedRect;//设置代理    _textField.delegate = self;//再次输入时清空   _textField.clearsOnBeginEditing = YES;//设置return功能    _textField.returnKeyType = UIReturnKeyDone;//添加点击事件    [_textField addTarget:self action:@selector(filter:) forControlEvents:UIControlEventEditingChanged];    self.navigationItem.titleView = _textField;

设置textfield的点击事件

#pragma mark - UITextField Delegate- (BOOL)textFieldShouldReturn:(UITextField *)textField{    [textField resignFirstResponder];    return YES;}

重点:textfield点击事件

- (void)filter:(UITextField *)textField{    //当输入框中没有输入内容时,搜索结果与原数据不变    if ([textField.text length] == 0) {        self.fontsArray = _data;        [self.tableView reloadData];        return;    }    //设置谓词内容    NSString *regex = [NSString stringWithFormat:@"SELF LIKE[c]'%@*'", textField.text];    NSPredicate *predicate = [NSPredicate predicateWithFormat:regex];    //将筛选后的结果传递到元数据数组中    self.fontsArray = [_data filteredArrayUsingPredicate:predicate];    [self.tableView reloadData];}

 

 
 

上一篇:iOS-常见问题

下一篇:闭包(block)

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表