UISearchBar increases navigation bar height in iOS 11

后端 未结 19 1586
醉酒成梦
醉酒成梦 2020-11-28 02:47

I have my UISearchBar being part of the navigation bar like:

 let searchBar = UISearchBar()
 //some more configuration to the search bar
 .....
         


        
19条回答
  •  情书的邮戳
    2020-11-28 02:59

    I believe in iOS 11 UISearchBar now has the height equals to 56, and UINavigationBar uses autolayout to fit its subviews hence it increases the height. If you still want to have UISearchBar as titleView as in pre-iOS 11, I found out the best way to do it is to embed UISearchBar in a custom view, and set this view's height to 44, and assign it to navigationItem.titleView

    class SearchBarContainerView: UIView {  
    
        let searchBar: UISearchBar  
    
        init(customSearchBar: UISearchBar) {  
            searchBar = customSearchBar  
            super.init(frame: CGRect.zero)  
    
            addSubview(searchBar)  
        }
    
        override convenience init(frame: CGRect) {  
            self.init(customSearchBar: UISearchBar())  
            self.frame = frame  
        }  
    
        required init?(coder aDecoder: NSCoder) {  
            fatalError("init(coder:) has not been implemented")  
        }  
    
        override func layoutSubviews() {  
            super.layoutSubviews()  
            searchBar.frame = bounds  
        }  
    }  
    
    class MyViewController: UIViewController {  
    
        func setupNavigationBar() {  
            let searchBar = UISearchBar()  
            let searchBarContainer = SearchBarContainerView(customSearchBar: searchBar)  
            searchBarContainer.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 44)  
            navigationItem.titleView = searchBarContainer  
        }  
    } 
    

提交回复
热议问题