IOS学习 UITableView 用谓词过滤

来源:互联网 发布:淘宝一件代发好做吗 编辑:程序博客网 时间:2024/06/06 00:09

@interface HomeTableViewController :UITableViewController<UITextFieldDelegate>

{

@private

    NSArray      *_fontsArray;

    NSArray      *_data;

    UITextField  *_textField;

}


@property (nonatomic,retain)NSArray *fontsArray;


@end




@implementation HomeTableViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    

    _fontsArray = [NSMutableArrayarrayWithArray:[UIFontfamilyNames]];

    _data = [UIFontfamilyNames];

    _textField = [[UITextFieldalloc]initWithFrame:CGRectMake(20,2, self.view.bounds.size.width-40,40)];

    _textField.borderStyle =UITextBorderStyleRoundedRect;

    _textField.delegate =self;

    _textField.returnKeyType =UIReturnKeyDone;

    _textField.clearsOnBeginEditing =YES;//清除上一次编辑内容

    [_textFieldaddTarget:selfaction:@selector(filter:)forControlEvents:UIControlEventEditingChanged];//值编辑时调用

    self.navigationItem.titleView =_textField;

}


- (void)filter:(UITextField *)sender{

    NSLog(@"---------");

    if (_textField.text ==nil) {

        self.fontsArray =_data;

        [self.tableViewreloadData];

        return;

    }else{

        NSString *str = [NSStringstringWithFormat:@"SELF LIKE [c]'%@*'",_textField.text];

         NSPredicate *predicate = [NSPredicatepredicateWithFormat:str];  //模糊查询

        self.fontsArray = [_datafilteredArrayUsingPredicate:predicate];

        [self.tableViewreloadData]; //整个表格重绘

    }

}


- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return_fontsArray.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier =@"cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    

    if (cell == nil) {

        cell = [[UITableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:cellIdentifier];

        UILabel *label = [[UILabelalloc]initWithFrame:CGRectMake(10,0, self.view.bounds.size.width-20,44)];

        label.tag = 101;

        label.backgroundColor = [UIColoryellowColor];

        [cell.contentView addSubview:label];

    }

    

    UILabel *label = (UILabel *)[cell.contentViewviewWithTag:101];

    label.text = _fontsArray[indexPath.row];

    

    return cell;

}


#pragma mark - UITextField Delegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    [textField resignFirstResponder]; //点击返回按钮时,失去第一响应

    return YES;

}


@end
0 0
原创粉丝点击