How can I set size leftBarButtonItem?

后端 未结 1 360
星月不相逢
星月不相逢 2020-12-11 09: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         


        
相关标签:
1条回答
  • 2020-12-11 09:44

    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

    0 讨论(0)
提交回复
热议问题