簡體   English   中英

SWIFT iOS9:如何識別單擊 UISearchBar 的 X 按鈕

[英]SWIFT iOS9: How to recognize a click on the X button of the UISearchBar

當用戶清除他正在搜索的單詞時,我必須更改 boolean 變量值。 當他點擊搜索欄右側的 X 圖標時,他將其清除。

我不知道如何獲得此操作。 與搜索欄相關的功能只識別點擊取消按鈕、書簽按鈕和搜索結果按鈕。

我如何在 iOS9 設備上使用 Swift 2 來做到這一點?

您可以實現UISearchBarDelegate的此委托函數:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
  if  searchText.count == 0 {
    //call your func
  }
}

如文檔所述:

Discussion
This method is also invoked when text is cleared from the search text field.

Swift 4 UISearchResultsUpdating委托方法:

func updateSearchResults(for searchController: UISearchController) 
{
    print("updating: \(searchController.searchBar.text!)")

    if (searchController.searchBar.text?.isEmpty)! 
    {
       print("empty")
    }
}
if let textfield = searchBar.value(forKey: "searchField") as? UITextField 
     textfield.delegate = self
}

首先,您可以將委托分配為此,然后在UITextFieldDelegate方法中

func textFieldShouldClear(_ textField: UITextField) -> Bool {
    searchBar.text = ""
    searchBar.resignFirstResponder()
    return true
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM