【问题标题】:iPhone perform action when UITextField / UISearchBar's clear button is pressed按下 UITextField / UISearchBar 的清除按钮时 iPhone 执行操作
【发布时间】:2011-01-25 04:26:42
【问题描述】:

当按下 UITextField / UISearchBar 上的“清除”按钮时,是否可以访问允许执行其他操作的委托方法?

谢谢

【问题讨论】:

标签: iphone uitextfield uisearchbar


【解决方案1】:

见:UITextFieldDelegate Protocol Reference

如果您将视图控制器设置为文本字段的委托(可以在界面生成器中完成),您可以使用:

- (void)clearSearchTextField
{
  ...
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
  if (textField == self.searchTextField) [self clearSearchTextField];
  return YES;
}

【讨论】:

    【解决方案2】:

    对于 Swift 3:

    在 UITextField 上按下“清除”按钮时执行操作

    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        if textField == yourTextFieldName {
            // do some action
        }
        return true
    }
    

    【讨论】:

      【解决方案3】:

      对于UISearchBar,您需要实现func searchBar(searchBar: UISearchBar, textDidChange searchText: String)

      这在func searchBarTextDidBeginEditing(searchBar: UISearchBar)func searchBar(searchBar: UISearchBar, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool 之前触发。

      你的实现应该是这样的:

      func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
              if searchText == "" {
                  //Code to execute when search is cleared
              }
          }
      

      【讨论】:

      • 它被调用,即使我用退格键清除文本。但是如何检测总明文呢?
      【解决方案4】:

      当您清除文本字段时,将发生几个事件,您可以通过 UISearchDisplayDelegate 或 UISearchBarDelegate(例如 searchBar:textDidChangesearchDisplayController:shouldReloadTableForSearchString)访问这些事件

      这也会导致搜索表隐藏,因此会触发

      searchDisplayController:willHideSearchResultsTableView  
      searchDisplayController:didHideSearchResultsTableView
      

      当搜索表隐藏时,您可以检查搜索文本是否为空,然后执行您需要执行的任何操作。

      【讨论】:

        【解决方案5】:

        在此处查看我的答案:https://stackoverflow.com/a/3852509/91458 - 它适用于 searchBar,但也应适用于 textField。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2010-09-24
          • 2011-10-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多