LoginSignup
0
0

More than 1 year has passed since last update.

SearchBarのScopeBarで検索機能作成

Posted at

今回の内容

1A383DF9-F4C7-4AC9-9499-A4B7EA40399B_1_105_c.jpeg 14B73BD8-FB35-47D4-A04B-99FCE2639812_1_105_c.jpeg

コードと簡単解説

ScopeBarを表示

  • searchController.searchBar.scopeButtonTitles = ["Vで検索","Fで検索","Cで検索"]で、ScopeBarに表示する値を決めます。

  • 下記のコードには書いていませんが、searchController.searchBar.showsScopeBar = Bool値について

    • trueだと、ScopeBarが常に表示された状態になります。
    • falseだと表示されなくなります。
    • searchController.searchBar.showsScopeBar = Bool値を書かない場合SearchBarをタップした時に、上の画像の様に表示されました。

           ~~~~~~~~~~省略~~~~~~~~~~
    let searchController = UISearchController()

    override func viewDidLoad() {
        super.viewDidLoad()

           ~~~~~~~~~~省略~~~~~~~~~~
        navigationItem.searchController = searchController
        searchController.searchBar.delegate = self
        searchController.searchBar.scopeButtonTitles = ["Vで検索","Fで検索","Cで検索"]
    }

ScopeBarがタップされた時の処理

  • func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {}は、ScopeBarがタップされた時に処理が働きます。

  • 今回の場合、一番左のScopeBarがタップされたと仮定すると,case 0内の処理が働きます。

    • searchController.searchBar.scopeButtonTitles[0]番目の値であるVで検索から.prefix(1)を使用して、最初の1文字目だけを取得します。(Vが取得される)
    • 取得してきた、1文字目が含まれているcellContentsArray内の値を全てsearchResultArrayに入れます。
    • titleには”V”で検索中と表示されます。
    • tableView.reloadData()でtableViewの表示を更新します。
func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

        switch selectedScope {

        case 0:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        case 1:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        case 2:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        default:
            searchResultArray = []
            title = "cellContentsArray"
            tableView.reloadData()
        }

    }

全てのコード

import UIKit

class ViewController: UIViewController{

    @IBOutlet weak var tableView: UITableView!

    let searchController = UISearchController()

    let cellContentsArray = ["UITableView","UISearchController","UIView","UIColor","UICollectionView","UISwich","UIKit","UITextField","UIViewController","UILabel"]

    var searchResultArray = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false

        title = "cellContentsArray"
        tableView.delegate = self
        tableView.dataSource = self

        searchController.searchBar.delegate = self
        searchController.searchBar.scopeButtonTitles = ["Vで検索","Fで検索","Cで検索"]
    }


}

extension ViewController:UISearchBarDelegate{

    func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {

        switch selectedScope {

        case 0:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        case 1:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        case 2:
            searchResultArray = []
            cellContentsArray.forEach { cellContent in

                if cellContent.contains(searchBar.scopeButtonTitles![selectedScope].prefix(1)){

                    searchResultArray.append(cellContent)
                    title = "”\(searchBar.scopeButtonTitles![selectedScope].prefix(1))”で検索中"
                    tableView.reloadData()
                }
            }

        default:
            searchResultArray = []
            title = "cellContentsArray"
            tableView.reloadData()
        }

    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        searchResultArray = []
        cellContentsArray.forEach { cellContent in

            if cellContent.contains(searchText) == true {

                searchResultArray.append(cellContent)
                title = "”\(searchText)”で検索中"
                tableView.reloadData()

            }else if searchText == ""{

                tableView.reloadData()
            }
        }
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {

        searchResultArray = []
        title = "cellContentsArray"
        tableView.reloadData()
    }

}

extension ViewController:UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return tableView.frame.size.height / 7   
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 1        
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return {() -> Int in

            switch searchResultArray.count > 0{

            case true: return searchResultArray.count

            case false: return cellContentsArray.count               
            }
        }()

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)

        cell.textLabel?.text = {() -> String in

            switch searchResultArray.count > 0{

            case true: return searchResultArray[indexPath.row]

            case false: return cellContentsArray[indexPath.row]
            }
        }()

        return cell
    }

}

終わり

ご指摘、ご質問などありましたら、コメントまでお願い致します。

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