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

查看:680
本文介绍了如何设置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面临从网址加载图片并将其设置为按钮图像的问题,我正在更新我的答案以证明相同,

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



<希望它有所帮助

Hope it helps

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

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