rejjer
rejjer

Reputation: 55

Swift UIBarButtonItem position that was created programatically

I create a button using SwiftIcons, but the position of the icon is not correct. I add a negative width to fix it:

let menuButton = UIBarButtonItem()
menuButton.setIcon(icon: .ionicons(.chevronLeft), iconSize: 24, color: .white, cgRect: CGRect(x: 0, y: 0, width: 24, height: 24), target: self, action: #selector(menuButtonClick))
let negativeSpacer:UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil)
negativeSpacer.width = -13.7;
self.navigationItem.leftBarButtonItems = [negativeSpacer, menuButton]

This works for iOS 10 or lower, but on iOS 11 the width does not take negative values.
Image
How can I fix this?

Answer:

let menuButton = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(menuButtonClick))
menuButton.image = UIImage.init(icon: .ionicons(.chevronLeft), size: CGSize(width: 24, height: 24))
menuButton.imageInsets = UIEdgeInsetsMake(0, -13.7, 0, 0)
self.navigationItem.leftBarButtonItem = menuButton

Upvotes: 1

Views: 1453

Answers (1)

Arrabidas92
Arrabidas92

Reputation: 1153

Maybe you can try by modifying edgeInsets for your button with this method :

UIEdgeInsets UIEdgeInsetsMake(CGFloat top, CGFloat left, CGFloat bottom, CGFloat right);

It allows you to add some padding on your barButtonItem. Here is how you can use it with your actual code :

negativeSpacer.imageInsets = UIEdgeInsetsMake(0, -13.7, 0, 0);

Upvotes: 2

Related Questions