iOS 11 SearchBar in NavigationBar

后端 未结 8 1880
陌清茗
陌清茗 2020-12-12 12:44

With iOS 11 Apple has redesigned the UISearchBar by making the corners rounder and the height bigger. Adding a UISearchBar to the navigationBar is pretty simple by just sett

8条回答
  •  一个人的身影
    2020-12-12 13:16

    If you really want to use the native UISearchBar (and avoid the needs of creating your custom components) in the iOS 11+ navigationBar, you could create a container view for that searchBar to have full control over the frame. This container view would be the superview of the searchBar you pass in.

    Something like:

    class SearchBarContainerView: UIView {
    
        let searchBar: UISearchBar
    
        required init?(coder aDecoder: NSCoder) {
            searchBar = UISearchBar()
            super.init(coder: aDecoder)
        }
    
        init(searchBar: UISearchBar) {
            self.searchBar = searchBar
            super.init(frame: CGRect(x: 0.0, y: 0.0, width: 0.0, height: 44.0))
            addSubview(searchBar)
        }
    
        override func layoutSubviews() {
            super.layoutSubviews()
            searchBar.frame = bounds
        }
    }
    

    And then:

    let containerView = SearchBarContainerView(searchBar: searchController.searchBar)
    containerView.frame.size.width = navigationController?.navigationBar.frame.size.width ?? 0.0
    navigationItem.titleView = containerView
    

    Note that this is just a quick demo and is not ready for navigationBar frame changes (display rotation etc.). You could solve that with e.g. autoresizingMask.

提交回复
热议问题