Change size of UIBarButtonItem (image) in Swift 3

前端 未结 6 2042
没有蜡笔的小新
没有蜡笔的小新 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:35

    This is how I did it

    iOS 10 and below

    func setUpMenuButton(){
        let menuBtn = UIButton(type: .custom)
        menuBtn.frame = CGRect(x: 0.0, y: 0.0, width: 20, height: 20)
        menuBtn.setImage(UIImage(named:"menuIcon"), for: .normal)
        menuBtn.addTarget(self, action: #selector(vc.onMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside)
    
        let menuBarItem = UIBarButtonItem(customView: menuBtn)
        self.navigationItem.leftBarButtonItem = menuBarItem
    }
    

    iOS 11 - Navigation bar come up with Autolayout so frame setting may not work

    func setUpMenuButton(){
        let menuBtn = UIButton(type: .custom)
        menuBtn.frame = CGRect(x: 0.0, y: 0.0, width: 20, height: 20)
        menuBtn.setImage(UIImage(named:"menuIcon"), for: .normal)
        menuBtn.addTarget(self, action: #selector(vc.onMenuButtonPressed(_:)), for: UIControlEvents.touchUpInside)
    
        let menuBarItem = UIBarButtonItem(customView: menuBtn)
        let currWidth = menuBarItem.customView?.widthAnchor.constraint(equalToConstant: 24)
        currWidth?.isActive = true
        let currHeight = menuBarItem.customView?.heightAnchor.constraint(equalToConstant: 24)
        currHeight?.isActive = true
        self.navigationItem.leftBarButtonItem = menuBarItem
    }
    

提交回复
热议问题