0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Swift】UISearchBarを利用してTableViewの表示を絞る

Last updated at Posted at 2021-03-06

UISearchBarでTableViewの表示を絞る方法

スクリーンショット 2021-03-06 17.12.18.png

1.storyboardでUISearchBarを配置し、ViewControllerと接続します。

@IBOutlet weak var searchBar: UISearchBar!

2.ViewControllerにUISearchBarDelegateプロコトルを適用させます。

class ViewController: UIViewController, UISearchBarDelegate{

3.searchBarの処理をコードで実装します。

// searchButtonを押した時に実行されるメソッド
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
     // tableViewに表示するデータリストをsearchBarに入力されたテキストで絞り込む
        members = members?.filter("name CONTAINS[cd] %@", searchBar.text!).sorted(byKeyPath: "name", ascending: true)
        tableView.reloadData()
    }
    
    // searchBarの入力が無くなったら絞り込みを解除する
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text?.count == 0 {
            loadMembers()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
    }
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?