iOS 使用UITextField自定義搜索框 實(shí)現(xiàn)用戶輸入完之后“實(shí)時(shí)搜索”功能
注:CSDN的代碼塊有點(diǎn)撈,如果瀏覽器窗口較窄,一行代碼占了兩行的位置,后面的代碼就看不到了,大家可以把瀏覽器窗口拉大一點(diǎn)
UI小姐姐設(shè)計(jì)的搜索框經(jīng)常是五花八門,系統(tǒng)的搜索框經(jīng)常不能滿足我們的需求,需要我們特別定制一個(gè)。但是UITextField的諸多回調(diào)里面,沒有一個(gè)是適合觸發(fā)搜索時(shí)間的。UITextFieldTextDidChangeNotification調(diào)用過于頻繁,每輸入一個(gè)字符就調(diào)一次接口怕是不太合適。UITextFieldTextDidEndEditingNotification只有在結(jié)束編輯的時(shí)候才會(huì)調(diào)一次,結(jié)束編輯就意味著鍵盤消失了,也不太合適。這樣就難倒我們了嗎,當(dāng)然不是,辦法還是有滴。
解決方案
先自定義一個(gè)搜索框 改好樣式,然后監(jiān)聽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; 記錄輸入次數(shù)- (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是為了防止用戶輸入完直接點(diǎn)擊搜索,延時(shí)結(jié)束之后又搜索一次 if (inputCount.integerValue == self.inputCount && self.inputCount != 0) { [self loadData]; }}- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [self loadData]; return NO;}- (void)loadData{ self.inputCount = 0;// 本地查詢 或者 請(qǐng)求數(shù)據(jù)... [self.tableView reloadData];}
核心代碼
延遲1.5秒以后執(zhí)行搜索,判讀如果1.5秒之后傳入的輸入次數(shù)和現(xiàn)在的輸入次數(shù)一致,說明用戶1.5秒已經(jīng)沒有輸入新內(nèi)容了,加在新數(shù)據(jù)。這個(gè)時(shí)間可以自己調(diào)整
[self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) afterDelay:1.5f];
總結(jié)
到此這篇關(guān)于iOS 使用UITextField自定義搜索框 實(shí)現(xiàn)用戶輸入完之后“實(shí)時(shí)搜索”功能的文章就介紹到這了,更多相關(guān)ios UITextField自定義搜索框 實(shí)時(shí)搜索內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 告別AJAX實(shí)現(xiàn)無刷新提交表單2. 博客日志摘要暨RSS技術(shù)3. JSP的Cookie在登錄中的使用4. ASP腳本組件實(shí)現(xiàn)服務(wù)器重啟5. ASP常用日期格式化函數(shù) FormatDate()6. JSP之表單提交get和post的區(qū)別詳解及實(shí)例7. SSM框架整合JSP中集成easyui前端ui項(xiàng)目開發(fā)示例詳解8. 解析原生JS getComputedStyle9. 使用XSL將XML文檔中的CDATA注釋輸出為HTML文本10. XML解析錯(cuò)誤:未組織好 的解決辦法
