Swift UIButton BarButtonItem中的图像大小失真

时间:2018-04-25 14:01:49

标签: swift uibutton uiimage uinavigationbar uibarbuttonitem

我想在UIButton添加navigationItem.leftBarButtonItem。 我希望UIButton24x24px并缩小图片。 但是按钮被扭曲了...如果我将UIImage更改为更小的图像,一切都很好。 - >看图片

scaleAspectFit ??

外,我该怎么办?
    let userProfilePic = UIButton()
    userProfilePic.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
    userProfilePic.setImage(UIImage(named: "profile_icon.jpg"), for: .normal)
    userProfilePic.contentMode = .scaleAspectFit
    userProfilePic.clipsToBounds = true
    userProfilePic.layer.borderWidth = 0.5
    userProfilePic.layer.borderColor = UIColor.white.cgColor
    userProfilePic.layer.cornerRadius = (userProfilePic.frame.size.width) / 2
    userProfilePic.addTarget(self, action: #selector(goToSettings), for: UIControlEvents.touchUpInside)

    self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: userProfilePic)

enter image description here


谢谢!

1 个答案:

答案 0 :(得分:1)

试试此代码

问题出现在ios 11+上,UIBarButtonItem在ios 11+其他使用框架上使用autolayout

     let userProfilePic = UIButton()
        userProfilePic.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
        userProfilePic.setImage(UIImage(named: "profile_icon.jpg"), for: .normal)
        userProfilePic.contentMode = .scaleToFill
        userProfilePic.clipsToBounds = true
        userProfilePic.layer.borderWidth = 0.5
        userProfilePic.layer.borderColor = UIColor.white.cgColor
        userProfilePic.layer.cornerRadius = (userProfilePic.frame.size.width) / 2

      if #available(iOS 11, *) {
    userProfilePic.widthAnchor.constraint(equalToConstant: 24.0).isActive = true
    userProfilePic.heightAnchor.constraint(equalToConstant: 24.0).isActive = true
      }

      userProfilePic.addTarget(self, action: #selector(goToSettings), for: UIControlEvents.touchUpInside)
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: userProfilePic)