skip to Main Content

I have a custom navigation bar with the superclass UINavigationBar with a custom navigation controller with the superclass UINavigationController. I added a button to the left side of my navigation bar. I also changed the navigation bar height and changed the button size in UIBarButtonItem. I use this code to do this:

class CustomNavigationViewController: UINavigationController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // change height

        let customNavigationBar = CustomNavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 68))
        view.addSubview(customNavigationBar)
        
        // change button size

        let customButton = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 44, height: 44))
        customButton.setImage(UIImage.init(named:"iOS2"), for: .normal)
        
        let customNavigationItem = UINavigationItem()
        customNavigationItem = UIBarButtonItem.init(customView: customButton)
        
        customNavigationBar.items = [customNavigationItem]
        
    }
}

class SLNavigationBar: UINavigationBar { 

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }
    
    private func commonInit() {
        backgroundColor = .white
    }

}

I get this result. In this case, the button top constraint = 0:

enter image description here

But I want to get this result (note the position of the green square), with button top constraint = 12:

enter image description here

How to change top UIBarButtonItem constraint?

2

Answers


  1. Try below.

    let customNavigationItem = UINavigationItem()
    var customBarItem = UIBarButtonItem.init(customView: customButton)
    button.setBackgroundVerticalPositionAdjustment(-20.0, for: .default)
    customNavigationItem = customBarItem
    

    Above code is used to change the ‘y’ position in this code. Change the ‘y’ value (here it is 12.0f) according to your requirement. If the value is positive, it will down the button position. If the value is negative, it will up your button position.

    Objective-C code used before is as below.

    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleDone target:self action:nil];
    [button setBackgroundVerticalPositionAdjustment:20.0f forBarMetrics:UIBarMetricsDefault];
    [[self navigationItem] setRightBarButtonItem:button];
    
    Login or Signup to reply.
  2. let customButton = UIButton.init(frame: CGRect.init(x: 0, y: 12, width: 44, height: 44))
    customButton.setImage(UIImage.init(named:"iOS2"), for: .normal)

    In above code customButton frame is set with a y position of 12 to achieve the top constraint.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search