user1079052
user1079052

Reputation: 3833

LeftBarButtonItem position is not correct

I am trying to add a leftbarbuttonitem like this: enter image description here

with this code:

let button = UIButton.init(type: .custom)
        button.setImage(UIImage.init(named: "WhiteBackButton.png"), for: UIControlState.normal)
        button.addTarget(self, action:#selector(self.backButtonSelected), for: UIControlEvents.touchUpInside)
        button.frame = CGRect.init(x: 0, y: 0, width: 30, height: 30)
        let barButton = UIBarButtonItem.init(customView: button)
        self.navigationItem.leftBarButtonItem = barButton

I am using this image: enter image description here

and it sends up looking pushed over like this:enter image description here

How do I stop it from pushing too far from the left?

Upvotes: 0

Views: 2902

Answers (2)

user1079052
user1079052

Reputation: 3833

let negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
        negativeSpacer.width = -10
        self.navigationItem.leftBarButtonItems = [negativeSpacer, leftBarButton]

Upvotes: 1

RLoniello
RLoniello

Reputation: 2329

WhiteBackButton.png image most likely has white space around/in front of the arrow.

I suggest also be using:

UIBarButtonItem(image:style:target:action:) instead of UIButton it will simplify your code...

https://developer.apple.com/reference/uikit/uibarbuttonitem/1617163-init

If you are changing the barButtonItems a lot can extend ViewController with the following functions and add them to viewWillAppear:

//should have a left and right of each:
func addRightBarButtonWithImage(_ buttonImage: UIImage) {
    let rightButton: UIBarButtonItem = UIBarButtonItem(image: buttonImage, style: UIBarButtonItemStyle.plain, target: self, action: #selector(self.toggleRight))
    navigationItem.rightBarButtonItem = rightButton
}


func setNavigationBarItem() {
    self.addLeftBarButtonWithImage(UIImage(named: “icon.png”)!)
    self.addRightBarButtonWithImage(UIImage(named: “icon.png”)!)

}

Hope this helps! Cheers!

Upvotes: 0

Related Questions