Change width of a UIBarButtonItem in a UINavigationBar

前端 未结 6 1625
囚心锁ツ
囚心锁ツ 2020-12-01 12:10

I am creating a UIBarButtonItem and adding it to my navigation bar like so:

(void)viewDidLoad { 

   ...

   // Add the refresh button to the navigation bar
         


        
6条回答
  •  一生所求
    2020-12-01 13:05

    Since iOS 11, just setting frame for customView and not UIBarButtonItem won't work (like suggested in accepted answer). It seems like adding Autolayout to UIBarButtonItem overrides the set frame. This post gave me the idea:

    navigationItem.leftBarButtonItem?.customView = yourCustomButtonView
    let desiredWidth = 35.0
    let desiredHeight = 35.0
    
    let widthConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredWidth)
    let heightConstraint = NSLayoutConstraint(item: yourCustomButtonView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: desiredHeight)
    
    yourCustomButtonView.addConstraints([widthConstraint, heightConstraint])
    

    Also note, that it is preferred that you use UIButton as your CustomView as you have to rely on it to trigger the action.

提交回复
热议问题