以编程方式创建的Swift UIBarButtonItem位置

时间:2017-09-29 22:01:36

标签: swift uibarbuttonitem ios11

我使用SwiftIcons创建一个按钮,但图标的位置不正确。我添加一个负宽度来修复它:

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]

适用于iOS 10或更低版本,但在iOS 11上,宽度不带负值 Image
我该如何解决这个问题?

答案:

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

1 个答案:

答案 0 :(得分:0)

也许您可以尝试使用此方法修改按钮的edgeInsets:

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

它允许您在barButtonItem上添加一些填充。 以下是如何将它与实际代码一起使用的方法:

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