iOS 使用UITextField自定义搜索框 实现用户输入完之后“实时搜索”功能
注:CSDN的代码块有点捞,如果浏览器窗口较窄,一行代码占了两行的位置,后面的代码就看不到了,大家可以把浏览器窗口拉大一点
UI小姐姐设计的搜索框经常是五花八门,系统的搜索框经常不能满足我们的需求,需要我们特别定制一个。但是UITextField的诸多回调里面,没有一个是适合触发搜索时间的。
UITextFieldTextDidChangeNotification调用过于频繁,每输入一个字符就调一次接口怕是不太合适。
UITextFieldTextDidEndEditingNotification只有在结束编辑的时候才会调一次,结束编辑就意味着键盘消失了,也不太合适。
这样就难倒我们了吗,当然不是,办法还是有滴。
解决方案
先自定义一个搜索框改好样式,然后监听UITextFieldTextDidChangeNotification
-(void)textFieldDidChange{
if(self.searchDelegate&&[self.searchDelegaterespondsToSelector:@selector(customSearchBar:textDidChange:)]){
[self.searchDelegatecustomSearchBar:selftextDidChange:self.text];
}
}
使用
@property(nonatomic,strong)LGCustomSearchBar*searchBar;
@property(nonatomic,assign)NSIntegerinputCount;记录输入次数
-(void)viewDidLoad{
[superviewDidLoad];
self.searchBar=[[LGCustomSearchBaralloc]initWithFrame:CGRectMake(20,10,kScreenWidth-40,36)];
self.searchBar.searchDelegate=self;
[self.viewaddSubview:self.searchBar];
}
-(void)customSearchBar:(LGCustomSearchBar*)searchBartextDidChange:(NSString*)searchText{
if(searchText.length==0){
[selfsearchKeyword:@(self.inputCount)];
}
else{
self.inputCount++;
[selfperformSelector:@selector(searchKeyword:)withObject:@(self.inputCount)afterDelay:1.5f];
}
}
-(void)searchKeyword:(NSNumber*)inputCount{
//判断不等于0是为了防止用户输入完直接点击搜索,延时结束之后又搜索一次
if(inputCount.integerValue==self.inputCount&&self.inputCount!=0){
[selfloadData];
}
}
-(BOOL)textFieldShouldReturn:(UITextField*)textField{
[selfloadData];
returnNO;
}
-(void)loadData{
self.inputCount=0;
//本地查询或者请求数据
...
[self.tableViewreloadData];
}
核心代码
延迟1.5秒以后执行搜索,判读如果1.5秒之后传入的输入次数和现在的输入次数一致,说明用户1.5秒已经没有输入新内容了,加在新数据。这个时间可以自己调整
[selfperformSelector:@selector(searchKeyword:)withObject:@(self.inputCount) afterDelay:1.5f];
总结
到此这篇关于iOS使用UITextField自定义搜索框实现用户输入完之后“实时搜索”功能的文章就介绍到这了,更多相关iosUITextField自定义搜索框实时搜索内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!