LoginSignup
4
7

More than 3 years have passed since last update.

[Swift 5]UISearchBarのクリアボタン(X)が押された時の動作を実装する

Posted at

UISearchBarを使ってインクリメンタルサーチを実装している時の備忘録です。

検索文字を入力すると、SearchBar内にクリアボタンが表示されます。

そのクリアボタンを押すと、入力テキストが削除されますが、

その時、検索結果を操作したいですよね。

しかし、検索した限りでは、UITextFieldでいうのtextFieldShouldClear(_ textField: UITextField) -> Boolのようなメソッドが見当たりませんでした。見逃しているだけだったら、すみません。

そこで、UISearchBarDelegateのsearchBar(_ searchBar: UISearchBar, textDidChange searchText: String)を使用することにしました。

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchText.isEmpty {
        results.removeAll()
    }
}

やっていることは極簡単です。

検索テキストが変更された時、検索文字列が空であれば、という条件を設ければOKです。

こうすることで、クリアボタンを押した際にif searchText.isEmptyの中身が実行されます。

参考:https://stackoverflow.com/questions/29135594/uisearchbar-x-button-pressed

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7