如何设置 leftBarButtonItem 的大小? [英] How can I set size leftBarButtonItem?

查看:15
本文介绍了如何设置 leftBarButtonItem 的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying set size programmatically of left button bar item but i can't it.

这是我的代码:

        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 中的结果.在图像中,您可以看到标题应用将其向右移动,因为按钮大小:

But this is the result in iphone X with Xcode 9 and swift 3. In the image, you can see title app move it to the right because button size:

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

Anybody know that the problem will be the image size??

推荐答案

您可以使用

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/

按钮的巨大框架是因为您为按钮的背景设置了巨大的图像.虽然您设置为按钮的框架应该覆盖按钮的隐式大小,但由于一些奇怪的原因,当作为自定义视图传递给栏按钮时,隐式大小会接管.因此,应用宽度和高度约束来限制自定义视图的大小成为必要.

The huge frame of the button is because of the huge image you are setting to the button's background. Though frame you set to button should override the implicit size of the button, for some strange Reasons when passed as custom view to bar button implicit size takes over. Hence applying width and height constraints to restrict the size of custom view kind of becomes necessary.

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

As OP is facing issue with loading the image from url and setting it as button's image I am updating my answer to demonstrate the same,

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

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

Issue with OP's code was trying to set the button image, even before the image was downloaded. So this should help you solve your problem :)

编辑 2:

OP 在使栏按钮的 customView 循环时遇到麻烦,所以这里是应该使 BarButton 项的 customView 循环的代码:)

OP facing trouble with making the bar button's customView circular, so here is the code that should make BarButton item's customView circular :)

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

希望能帮到你

这篇关于如何设置 leftBarButtonItem 的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆