久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

iOS 使用UITextField自定義搜索框 實現用戶輸入完之后“實時搜索”功能

瀏覽:66日期:2022-09-17 10:48:21

注: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自定義搜索框 實時搜索內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: IOS
相關文章:
主站蜘蛛池模板: 宣恩县| 三原县| 喀什市| 徐州市| 旬阳县| 商丘市| 东源县| 兰西县| 榆社县| 冀州市| 延安市| 沐川县| 当阳市| 石楼县| 尉犁县| 明光市| 鹤岗市| 丹巴县| 永寿县| 汤原县| 德阳市| 金寨县| 北流市| 抚宁县| 九江县| 巴青县| 馆陶县| 衡水市| 喀喇| 博野县| 新建县| 汝城县| 新津县| 博白县| 望城县| 鸡东县| 华亭县| 松潘县| 安丘市| 清水河县| 木兰县|