Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

ios - How can I set size leftBarButtonItem?

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:

enter image description here

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...