7
5

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 5 years have passed since last update.

iOS13バグ:UISearchBarをNavigation BarのtitleViewに表示させているときに高さが変わって画面遷移時に隙間があく問題

Posted at

現象

画面遷移後にこんな隙間が出来てしまう。

対処法

UISearchBarの中身の高さがなぜが56になってしまってどうにもコントロールができなかった。
stackoverflowに書いてあった遷移時に高さを調整する方法で解決

    // iOS13でuisearchbarをnavigationItem.titleViewに置き換えるとheightが56になってしまう課題の対処
    // https://stackoverflow.com/a/47976999/4652214
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.view.setNeedsLayout() // force update layout
        navigationController?.view.layoutIfNeeded() // to fix height of the navigation bar
    }

おまけ関連のコード全体

    func setupSearchBar() {
        self.extendedLayoutIncludesOpaqueBars = true
        if let navigationBarFrame = navigationController?.navigationBar.bounds {
            let searchBar: UISearchBar = UISearchBar(frame: navigationBarFrame)
            // iphone xでUISearchBarのheightが大きくなってしまう対策 参考 : https://stackoverflow.com/questions/46318022/uisearchbar-increases-navigation-bar-height-in-ios-11
            if #available(iOS 11.0, *) {
                searchBar.heightAnchor.constraint(equalToConstant: 44).isActive = true
            }
            
            searchBar.delegate = self
            searchBar.placeholder = "キーワードでさがす"
            searchBar.keyboardType = UIKeyboardType.default
            navigationItem.titleView = searchBar
            navigationItem.titleView?.frame = searchBar.frame
            self.searchBar = searchBar
        }
    }

    // iOS13でuisearchbarをnavigationItem.titleViewに置き換えるとheightが56になってしまう課題の対処法
    // https://stackoverflow.com/a/47976999/4652214
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.view.setNeedsLayout() // force update layout
        navigationController?.view.layoutIfNeeded() // to fix height of the navigation bar
    }
7
5
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
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?