How can I set size leftBarButtonItem?

一世执手 提交于 2019-11-27 07:21:20

问题


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

This is my code:

        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)

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??


回答1:


You can restrict the size of barButton items using

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

Reference : 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.

EDIT:

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)
    } 

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 :)

EDIT 2:

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



来源:https://stackoverflow.com/questions/48048852/how-can-i-set-size-leftbarbuttonitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!