How to change the size of titleView in navigation bar. Because there's a gap between titleView and backButton in navigationBar

后端 未结 3 704
清歌不尽
清歌不尽 2021-01-02 12:46

I\'ve added a search bar to my navigation.titleView

    self.navigationItem.titleView = searchBar

There\'s also a BackBarButtonItem with ti

3条回答
  •  自闭症患者
    2021-01-02 13:28

    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  
      }  
    }
    

提交回复
热议问题