iOS 使用UITextField自定義搜索框 實現(xiàn)用戶輸入完之后“實時搜索”功能
注:CSDN的代碼塊有點撈,如果瀏覽器窗口較窄,一行代碼占了兩行的位置,后面的代碼就看不到了,大家可以把瀏覽器窗口拉大一點
UI小姐姐設計的搜索框經(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é)
到此這篇關于iOS 使用UITextField自定義搜索框 實現(xiàn)用戶輸入完之后“實時搜索”功能的文章就介紹到這了,更多相關ios UITextField自定義搜索框 實時搜索內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持好吧啦網(wǎng)!
相關文章:
1. Java Media Framework 基礎教程2. 解決vue頁面刷新,數(shù)據(jù)丟失的問題3. Python 忽略文件名編碼的方法4. springboot項目整合druid數(shù)據(jù)庫連接池的實現(xiàn)5. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis6. python 讀txt文件,按‘,’分割每行數(shù)據(jù)操作7. android studio實現(xiàn)簡單的計算器(無bug)8. 在Mac中配置Python虛擬環(huán)境過程解析9. Python趣味挑戰(zhàn)之用pygame實現(xiàn)簡單的金幣旋轉(zhuǎn)效果10. Python中的min及返回最小值索引的操作
