Adjust position of bar button item when using large titles with iOS 11

后端 未结 5 1110
暗喜
暗喜 2021-02-05 06:32

I am using the large title navbar with iOS 11, but when I add a bar button item it looks weird positioned in the same location as the original title navbar. I would like to move

5条回答
  •  自闭症患者
    2021-02-05 06:42

    To solve my own problem, I just added a button as a subview of the navbar and set the right and bottom constraints to the navbar. The button will now move up and down when the navbar changes size. However, this requires the button to be removed in any view controllers that you show segue from this view controller. Thus, I added a tag of 1 to the button and removed it from its superview from the other view controller. This is the easiest way to solve it, and I found it the easiest method.

    To setup the right button:

    func setupNavBar() {
    
        self.title = "Home"
        self.navigationController?.navigationBar.prefersLargeTitles = true
        self.navigationController?.navigationBar.isTranslucent = false
    
        let searchController = UISearchController(searchResultsController: nil)
        self.navigationItem.searchController = searchController
    
        let rightButton = UIButton()
        rightButton.setTitle("Right Button", for: .normal)
        rightButton.setTitleColor(.purple, for: .normal)
        rightButton.addTarget(self, action: #selector(rightButtonTapped(_:)), for: .touchUpInside)
        navigationController?.navigationBar.addSubview(rightButton)
        rightButton.tag = 1
        rightButton.frame = CGRect(x: self.view.frame.width, y: 0, width: 120, height: 20)
    
        let targetView = self.navigationController?.navigationBar
    
        let trailingContraint = NSLayoutConstraint(item: rightButton, attribute:
            .trailingMargin, relatedBy: .equal, toItem: targetView,
                             attribute: .trailingMargin, multiplier: 1.0, constant: -16)
        let bottomConstraint = NSLayoutConstraint(item: rightButton, attribute: .bottom, relatedBy: .equal,
                                        toItem: targetView, attribute: .bottom, multiplier: 1.0, constant: -6)
        rightButton.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([trailingContraint, bottomConstraint])
    
    }
    

    To remove it from any show segued view controllers:

    func removeRightButton(){
        guard let subviews = self.navigationController?.navigationBar.subviews else{return}
        for view in subviews{
            if view.tag != 0{
                view.removeFromSuperview()
            }
        }
    } 
    

    Both functions are called in the viewWillAppear function

提交回复
热议问题