Change size of UIBarButtonItem (image) in Swift 3

前端 未结 6 2050
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 07:51

I am trying to change the size of some icons in my navBar, but I am a little confused as to how to do this? My code so far is:

func setUpNavBarButtons() {
          


        
6条回答
  •  别那么骄傲
    2020-12-14 08:26

    @DogCoffee answer is a great and creative way to solve the problem. May I suggest some slightly mods in order to take into account size and tintColor

    extension UIBarButtonItem {
    
        static func menuButton(_ target: Any?,
                               action: Selector,
                               imageName: String,
                               size:CGSize = CGSize(width: 32, height: 32),
                               tintColor:UIColor?) -> UIBarButtonItem
        {
            let button = UIButton(type: .system)
            button.tintColor = tintColor
            button.setImage(UIImage(named: imageName), for: .normal)
            button.addTarget(target, action: action, for: .touchUpInside)
    
            let menuBarItem = UIBarButtonItem(customView: button)
            menuBarItem.customView?.translatesAutoresizingMaskIntoConstraints = false
            menuBarItem.customView?.heightAnchor.constraint(equalToConstant: size.height).isActive = true
            menuBarItem.customView?.widthAnchor.constraint(equalToConstant: size.width).isActive = true
    
            return menuBarItem
        }
    }
    

提交回复
热议问题