iOS 使用UITextField自定義搜索框 實現(xiàn)用戶輸入完之后“實時搜索”功能
注:CSDN的代碼塊有點撈,如果瀏覽器窗口較窄,一行代碼占了兩行的位置,后面的代碼就看不到了,大家可以把瀏覽器窗口拉大一點
UI小姐姐設(shè)計的搜索框經(jīng)常是五花八門,系統(tǒng)的搜索框經(jīng)常不能滿足我們的需求,需要我們特別定制一個。但是UITextField的諸多回調(diào)里面,沒有一個是適合觸發(fā)搜索時間的。UITextFieldTextDidChangeNotification調(diào)用過于頻繁,每輸入一個字符就調(diào)一次接口怕是不太合適。UITextFieldTextDidEndEditingNotification只有在結(jié)束編輯的時候才會調(diào)一次,結(jié)束編輯就意味著鍵盤消失了,也不太合適。這樣就難倒我們了嗎,當然不是,辦法還是有滴。
解決方案
先自定義一個搜索框 改好樣式,然后監(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是為了防止用戶輸入完直接點擊搜索,延時結(jié)束之后又搜索一次 if (inputCount.integerValue == self.inputCount && self.inputCount != 0) { [self loadData]; }}- (BOOL)textFieldShouldReturn:(UITextField *)textField{ [self loadData]; return NO;}- (void)loadData{ self.inputCount = 0;// 本地查詢 或者 請求數(shù)據(jù)... [self.tableView reloadData];}
核心代碼
延遲1.5秒以后執(zhí)行搜索,判讀如果1.5秒之后傳入的輸入次數(shù)和現(xiàn)在的輸入次數(shù)一致,說明用戶1.5秒已經(jīng)沒有輸入新內(nèi)容了,加在新數(shù)據(jù)。這個時間可以自己調(diào)整
[self performSelector:@selector(searchKeyword:) withObject:@(self.inputCount) afterDelay:1.5f];
總結(jié)
到此這篇關(guān)于iOS 使用UITextField自定義搜索框 實現(xiàn)用戶輸入完之后“實時搜索”功能的文章就介紹到這了,更多相關(guān)ios UITextField自定義搜索框 實時搜索內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP基礎(chǔ)知識Command對象講解2. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容3. JavaScrip簡單數(shù)據(jù)類型隱式轉(zhuǎn)換的實現(xiàn)4. 解決ajax請求后臺,有時收不到返回值的問題5. jsp+mysql實現(xiàn)網(wǎng)頁的分頁查詢6. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁7. ASP中實現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)8. XHTML 1.0:標記新的開端9. JSP 中request與response的用法詳解10. asp知識整理筆記4(問答模式)
