如何设置leftBarButtonItem的大小?

我正在尝试以编程方式设置左键按钮项目的大小,但我不能。

这是我的代码:

let backButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30)) backButton.setBackgroundImage(UIImage(named: "hipster_pelo2.png"), for: .normal) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton) 

但这是iphone X与Xcode 9和swift 3的结果。在图像中,您可以看到标题应用程序将其移动到右侧,因为按钮大小:

在此处输入图像描述

有谁知道问题将是图像大小??

您可以使用限制barButton项的大小

 let barButton = UIBarButtonItem(customView: backButton) NSLayoutConstraint.activate([(barButton.customView!.widthAnchor.constraint(equalToConstant: 30)),(barButton.customView!.heightAnchor.constraint(equalToConstant: 30))]) self.navigationItem.leftBarButtonItem = barButton 

参考: https : //skyebook.net/blog/2017/09/uibarbuttonitem-sizing-in-ios-11/

按钮的巨大框架是因为您设置按钮背景的巨大图像。 虽然您设置为按钮的帧应覆盖按钮的隐式大小,但对于某些奇怪的原因,当自定义视图传递到条形按钮时,隐式大小会占用。 因此,应用宽度和高度约束来限制自定义视图类型的大小变得必要。

编辑:

由于OP面临从url加载图像并将其设置为按钮图像的问题,我正在更新我的答案以演示相同的,

  do { try button.setImage(UIImage(data: Data(contentsOf: your_url)), for: .normal) } catch { print(error) } 

OP的代码问题是尝试设置按钮图像,甚至在下载图像之前。 所以这应该可以帮助你解决问题:)

编辑2:

OP在制作条形按钮的customView循环时遇到麻烦,所以这里的代码应该是BarButton项目的customView循环:)

  barButton.customView?.layer.cornerRadius = 15 barButton.customView?.layer.masksToBounds = true 

希望能帮助到你

Interesting Posts