0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift TableViewを検索してデータを絞り込む(Realm使用)

Posted at

はじめに

Realmで保存してあるデータがTableViewに既に表示されている状態のとき、UISearchBarを用いた検索機能を実現したいと考えている人向けの記事です。Realmをデータベースとして用いたのでこのように謳っていますが、別にRealmじゃなくてもやることは一緒です。

コード

今回はUISearchbarの文字列が変わる度に検索をかけるときを想定しています。
肝心の絞り込みはRealmの.filter関数を用いています。
何を用いてデータを保存しているかに応じてフィルタリングを行うときの関数の形は変わりますが、変わるのはそれだけで、

  1. 文字列に応じてフィルタリングを行う
  2. 上記の結果を配列に格納する
  3. tableViewをリロードする

の手順を踏めばOKです。

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text?.count == 0 { // 検索されている文字列がない時
            configureTableView()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        } else {
            let realm = try! Realm()
            self.itemList = realm.objects(TimeCapsuleModel.self).filter("title CONTAINS[cd] %@", searchBar.text!) //itemListにフィルタリングした結果を格納する
        }
        tableView.reloadData()
    }
    func configureTableView() {
        let realm = try! Realm()
        self.itemList = realm.objects(TimeCapsuleModel.self)
        
        self.tableView.reloadData()
    }
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?