我想在UIButton
添加navigationItem.leftBarButtonItem
。
我希望UIButton
为24x24px
并缩小图片。
但是按钮被扭曲了...如果我将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)
答案 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)