Help us understand the problem. What is going on with this article?

ナビゲーションバーに UISearchBar を ScopeBar 付きで表示

More than 3 years have passed since last update.

ナビゲーションバーに UISearchBar を載せ、編集中のみ ScopeBar を表示する。

標準 編集中
UISearchBar.png UISearchBar+Editing.png

コードサンプルは以下の通り。高さの調整はもっとマシな方法があるかもしれない。

    override func viewDidLoad() {
        super.viewDidLoad()

        let searchBar = UISearchBar()
        searchBar.delegate = self
        searchBar.scopeBarBackgroundImage = UIImage() // 空の画像をセットしないと親 View に背景色がつく
        self.navigationItem.titleView = searchBar
    }

    // MARK: - UISearchBarDelegate

    func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
        searchBar.showsCancelButton = true
        searchBar.scopeButtonTitles = ["A", "B"]
        searchBar.showsScopeBar = true
        self.navigationController?.navigationBar.frame.size.height = 84
        return true
    }

    func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
        searchBar.showsCancelButton = false
        searchBar.scopeButtonTitles = [] // 空にしないと showsScopeBar = false にしても表示される
        searchBar.showsScopeBar = false
        self.navigationController?.navigationBar.frame.size.height = 44
        return true
    }

    func searchBarCancelButtonClicked(searchBar: UISearchBar) {
        searchBar.text = ""
        searchBar.resignFirstResponder()
    }

kleerd
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away