【问题标题】:Swift UIButton Image size distorted in BarButtonItemSwift UIButton 图像大小在 BarButtonItem 中失真
【发布时间】:2018-10-06 01:12:23
【问题描述】:

我想将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)




谢谢!

【问题讨论】:

    标签: swift uibutton uiimage uinavigationbar uibarbuttonitem


    【解决方案1】:

    试试这个代码

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2017-11-22
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多