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:
But I want to get this result (note the position of the green square), with button top constraint = 12:
How to change top UIBarButtonItem
constraint?
2
Answers
Try below.
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.
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.