[英]How to fire UISearchBar delegate single time?
當用戶在uisearchbar中鍵入文本時,我正在過濾一個數組,但問題是我有一個警報處理程序,每次調用該委托時都會觸發該警報處理程序,但是我希望警報僅一次出現而不是多次出現。代碼在下面
-(void)searchBar:(UISearchBar )searchBar textDidChange:(NSString )searchText {
if(searchText.length == 0)
{
_isFiltered = FALSE;
}
else{
// NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:@"(SELF.name contains[cd] %@)or(SELF.rank contains[cd] %@)or(SELF.score contains[cd] %@)",searchText,searchText,searchText];
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:@"(SELF contains[cd] %@)",searchText];
self.filteredTableData = [self.searchItemsArray filteredArrayUsingPredicate:resultPredicate];
NSLog(@"Predicated array %@", self.filteredTableData);
self.isFiltered = YES;
if (self.filteredTableData.count == 0) {
[[CLAlertHandler standardAlertHandler]showAlert:@"No match found!" title:AppName];
[self.searchTableView reloadData];
}
}
//[self.searchTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
[self.searchTableView reloadData];
}
每次調用委托方法時,請使用-[NSNotification enqueueNotification…]
向自己發布通知,並帶有NSPostWhenIdle
優先級(例如)和合並掩碼。 這將合並這些通知並在系統空閑時將其觸發,在這種情況下,您可以在用戶不直接鍵入內容時進行工作。
在您的實施文件中:
const NSString *myNotificationName = @"kMyNotificationName";
在viewWillAppear
,或類似的:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleSearchFieldUpdate:)
name:myNotificationName object:self];
在委托方法中:
[[NSNotificationQueue defaultQueue] enqueueNotification:[NSNotification notificationWithName:myNotificationName object:self]
postingStyle:NSPostWhenIdle
coalesceMask:NSNotificationCoalescingOnName
forModes:nil];
作為新的類方法:
- (void)handleSearchFieldUpdate:(NSNotification *)notification {
.. do your work ..
}
最終結果將是每次用戶停止鍵入時都會調用選擇器handleSearchFieldUpdate
。
為什么沒有布爾變量來確定警報是否之前已顯示?
@interface ViewController() { //extension in .m file
BOOL noResultsAlertShown;
}
然后
if (self.filteredTableData.count == 0 && !noResultsAlertShown) {
noResultsAlertShown = YES;
[[CLAlertHandler standardAlertHandler]showAlert:@"No match found!" title:AppName];
[self.searchTableView reloadData];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.