当由于编辑或由于第一响应者而调用updateSearchResultsForSearchController时如何分离

问题描述 投票:0回答:2

the documentation写的是方法

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController

在两种情况下调用:当搜索栏成为第一个响应者或用户在搜索栏内进行更改时。

可以使第一响应者辞职:

[complaintSearchController.searchBar resignFirstResponder];

但是,是否有可能仅在用户编辑搜索栏中的文本的情况下调用customMethod?

代码如上:

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    [self customMethod];
}

也许可以使用任何条件语句检测状态:

-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
  if (condition){
      [self customMethod];
  }
}

例如,if([complaintSearchController.searchBar isFirstResponder])没有涵盖它。

基本上,我需要在调用此方法时将这两种情况分开。

ios objective-c uisearchcontroller
2个回答
0
投票

我会尝试在您的搜索控制器的协议UISearchResultsUpdating上触发的NSNotification。然后,您可以在目标中为NSNotification设置该方法。

 - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
    {
       [[NSNotificationCenter defaultCenter] postNotificationName:@"CustomName" object:nil];
      //or potentially you could just call your custom method directly
    }

只要搜索栏成为第一响应者或对搜索栏中的文本进行了更改,就会自动调用此方法。在此方法内执行任何所需的过滤和更新。

[[NSNotificationCenter defaultCenter] addObserver:self
                                      selector:@selector(customMethod)
                                                 name:@"CustomName"
                                               object:nil];

也许保存用户输入的最后状态,然后通过执行isEqualToString检查文本是否已更改:


0
投票

我会在View Controller中添加一个状态:

private var vmSearchBarInputDidChange: Bool = false

在“-DidChange”UISearchBarDelegate方法中将此值设置为true,即:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int)

现在在updateSearchResults函数中,我们可以:

guard vmSearchBarInputDidChange else { return }

在做实际搜索之前。

执行搜索后,在退出之前重置状态:

vmSearchBarInputDidChange = false // reset
© www.soinside.com 2019 - 2024. All rights reserved.