Swift UIButton BarButtonItem 中图像大小扭曲

标签 swift uibutton uiimage uinavigationbar uibarbuttonitem

我想向 navigationItem.leftBarButtonItem 添加一个 UIButton。 我希望 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)

enter image description here


谢谢!

最佳答案

试试这个代码

这个问题出现在ios 11+上,UIBarButtonItem在ios 11+其他使用框架上使用自动布局

     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)

关于Swift UIButton BarButtonItem 中图像大小扭曲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024301/

相关文章:

swift - 有没有办法模拟 View ?

iphone - 触摸时如何以编程方式更改按钮的背景图像?

ios - 按下时以编程方式移除 UIBarButtonItem 上的灯光?

ios - 签名捕获 IOS

objective-c - 错误 : 'archiver has finished; cannot encode anything more'

ios - Swift Firebase - 返回提要中所有用户事件的结果

ios - 推送新的 UIViewController 时 UISearchController 消失

objective-c - 从另一个 iOS 中减去一个图像

ios - 如何制作动态 uitabbar Controller ?(swift)

ios - 自定义按钮不响应触摸 - 快速