iOS UITextField实现实时搜索功能
创建textField
self.searchTabble.tableHeaderView = bgView;
self.searchFIeld = [[UITextField alloc]init];
self.searchFIeld.frame = CGRectMake(15*SCREEN_SCALE, 10*SCREEN_SCALE, SCREENW-30*SCREEN_SCALE, 34*SCREEN_SCALE);
[self setRightViewWithTextField:self.searchFIeld imageName:@"搜索"];
self.searchFIeld.placeholder = @"请输入停车场名称";
self.searchFIeld.borderStyle= UITextBorderStyleRoundedRect;
self.searchFIeld.keyboardType = UIKeyboardTypeWebSearch;
[self.searchFIeld addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];
self.searchFIeld.delegate = self;
self.searchFIeld.clearButtonMode = UITextFieldViewModeWhileEditing;
[bgView addSubview:self.searchFIeld];
实现代理方法
- (void)textFieldDidChange {
if (self.searchFIeld.text != nil && self.searchFIeld.text.length > 0) {
self.listFilterTeamsArray = [NSMutableArray array];
for (NSMutableDictionary *dic in self.parkArray) {
NSString * name = [dic objectForKey:@"parkName"];
if ([name rangeOfString:self.searchFIeld.text options:NSCaseInsensitiveSearch].length > 0) {
[self.listFilterTeamsArray addObject:dic];
[self.searchTabble reloadData];
}
}
}
[self.searchTabble reloadData];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
self.searchFIeld.text=@"";
[self.historyArray removeAllObjects];
[self.searchTabble reloadData];
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
[self.searchTabble reloadData];
}
核心功能如此,根据字段文字进行搜索实时显示,不搜索显示全部,搜索显示相关内容,不需要后台,直接客户端实现。文中变量自行脑补。
是不是一目了然。简单粗暴,每天更新一个iOS小功能,喜欢的记得点赞加关注哦