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

后端 未结 3 671
清歌不尽
清歌不尽 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:41

    override func viewDidLoad() {
        super.viewDidLoad()
    
        let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 22))
    
        let searchBar = UISearchBar()
        searchBar.translatesAutoresizingMaskIntoConstraints = false
        container.addSubview(searchBar)
    
        let leftButtonWidth: CGFloat = 35 // left padding
        let rightButtonWidth: CGFloat = 75 // right padding
        let width = view.frame.width - leftButtonWidth - rightButtonWidth
        let offset = (rightButtonWidth - leftButtonWidth) / 2
    
        NSLayoutConstraint.activate([
            searchBar.topAnchor.constraint(equalTo: container.topAnchor),
            searchBar.bottomAnchor.constraint(equalTo: container.bottomAnchor),
            searchBar.centerXAnchor.constraint(equalTo: container.centerXAnchor, constant: -offset),
            searchBar.widthAnchor.constraint(equalToConstant: width)
        ])
    
    
        self.navigationItem.titleView = container
    }
    

提交回复
热议问题