こんにちは、のっくんです。
iPhoneアプリの開発で学んだことをアウトプットしていきます。
TableViewを検索する方法について説明していきたいと思います。
出来上がったイメージは以下の通り。

記事を集めるアプリですが、自分の好きな言葉で検索するような機能を実装してみました。
SearchBarを使って文字列を検索しています。
StoryBoard
StoryBoardは以下の通り。
Tableの中に検索バーを配置します。

ViewController
次にViewVontrollerを実装していきます。
UISearchBarDelegate
を継承します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class MyViewController: UITableViewController, ArticleCellDelegate,UISearchBarDelegate{ @IBOutlet weak var spinner: UIActivityIndicatorView! @IBOutlet var table: UITableView! @IBOutlet weak var search: UISearchBar! let myRefreshControl = UIRefreshControl() var items = [Item]() var currentItems = [Item]() func setupSearchBar(){ search.delegate = self } func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { } // 検索バーに入力があったら呼ばれる func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { guard !searchText.isEmpty else { currentItems = items table.reloadData() return } currentItems = items.filter({ item -> Bool in item.title.lowercased().contains(searchText.lowercased()) }) table.reloadData() } |
記事やリンクをItemクラスで管理していますが、オブジェクト配列を2つ(itemsとcurrentItems)用意します。
currentItemsには検索された記事のオブジェクト、itemsには全記事のオブジェクトを格納するようにします。
searchBarの中身ですが、
- 入力された文字列が空であれば、itemsを表示する
- 入力された文字列が空でなければ、文字列が含まれる記事のオブジェクトを検索する
最後にリロードをしてテーブルを更新します。
TableView
tableViewのコードも更新します。
itemsではなくcurrentItemsを表示するように変更します。
1 2 3 4 5 6 7 8 9 10 11 12 |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return currentItems.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! MyTableViewCell let row_item = currentItems[indexPath.row] cell.setArticle(item: row_item) return cell } |
参考
この記事で紹介したコードは以下のビデオを参考にしています。