iOS 使用UITextField自定義搜索框 實現用戶輸入完之后“實時搜索”功能
注: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];
總結
到此這篇關于iOS 使用UITextField自定義搜索框 實現用戶輸入完之后“實時搜索”功能的文章就介紹到這了,更多相關ios UITextField自定義搜索框 實時搜索內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: