【问题标题】:How can I set size leftBarButtonItem?如何设置大小 leftBarButtonItem?
【发布时间】:2018-01-01 10:22:48
【问题描述】:

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

这是我的代码:

        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)

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

有人知道问题出在图片大小吗??

【问题讨论】:

  • 请看一下发布的答案,让我知道您是否需要帮助
  • 请检查并确认Edit 2是否解决了您的圆形图像问题

标签: ios iphone swift3 uibarbuttonitem


【解决方案1】:

您可以使用来限制 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 在制作 bar 按钮的 customView 循环时遇到问题,所以这里是应该使 BarButton 项的 customView 循环的代码:)

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

希望对你有帮助

【讨论】:

  • 感谢节省了我的时间 :) NSLayoutConstraint.activate 这条线起到了神奇的作用:D
猜你喜欢
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多