iOS 使用UITextField自定义搜索框 实现用户输入完之后“实时搜索”功能

来自:互联网
时间:2020-05-26
阅读:

注:CSDN的代码块有点捞,如果浏览器窗口较窄,一行代码占了两行的位置,后面的代码就看不到了,大家可以把浏览器窗口拉大一点

UI小姐姐设计的搜索框经常是五花八门,系统的搜索框经常不能满足我们的需求,需要我们特别定制一个。但是UITextField的诸多回调里面,没有一个是适合触发搜索时间的。
UITextFieldTextDidChangeNotification调用过于频繁,每输入一个字符就调一次接口怕是不太合适。
UITextFieldTextDidEndEditingNotification只有在结束编辑的时候才会调一次,结束编辑就意味着键盘消失了,也不太合适。
这样就难倒我们了吗,当然不是,办法还是有滴。

解决方案

先自定义一个搜索框 改好样式,然后监听UITextFieldTextDidChangeNotification

- (void)textFieldDidChange{
 if (self.searchDelegate && [self.searchDelegate respondsToSelector:@selector(customSearchBar:textDidChange:)]) {
 [self.searchDelegate customSearchBar:self textDidChange:self.text];
 }
}

使用

@property (nonatomic, strong) LGCustomSearchBar *searchBar;
@property (nonatomic, assign) NSInteger inputCount; 记录输入次数

- (void)viewDidLoad {
 [super viewDidLoad];
 self.searchBar = [[LGCustomSearchBar alloc] initWithFrame:CGRectMake(20, 10, kScreenWidth-40, 36)];
 self.searchBar.searchDelegate = self;
 [self.view addSubview:self.searchBar];
}
- (void)customSearchBar:(LGCustomSearchBar *)searchBar textDidChange:(NSString *)searchText{
 if (searchText.length == 0) {
 [self searchKeyword:@(self.inputCount)];
 }
 else{
 self.inputCount++;
 [self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) afterDelay:1.5f];
 }
}
- (void)searchKeyword:(NSNumber *)inputCount{
	// 判断不等于0是为了防止用户输入完直接点击搜索,延时结束之后又搜索一次
 if (inputCount.integerValue == self.inputCount && self.inputCount != 0) {
 [self loadData];
 }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
 [self loadData];
 return NO;
}
- (void)loadData{
 self.inputCount = 0;
	// 本地查询 或者 请求数据
	...
 [self.tableView reloadData];
}

核心代码

延迟1.5秒以后执行搜索,判读如果1.5秒之后传入的输入次数和现在的输入次数一致,说明用户1.5秒已经没有输入新内容了,加在新数据。这个时间可以自己调整

[self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) 
afterDelay:1.5f];
返回顶部
顶部