rejjer rejjer - 3 years ago 142
Swift Question

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download