【问题标题】:CustomView UIBarButtonItem works for all phones other than iPhone 6CustomView UIBarButtonItem 适用于 iPhone 6 以外的所有手机
【发布时间】:2018-07-04 08:29:10
【问题描述】:

我使用以下代码创建了一个带有自定义视图的UIBarButtonItem(我将profileImageButton 框架的尺寸指定为40x40)。

let profileImageButton = UIButton(type: .custom)
profileImageButton.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
profileImageButton.setImage(imageCache.getProfileImage(), for: .normal)
profileImageButton.layer.cornerRadius = 20
profileImageButton.layer.masksToBounds = true
profileImageButton.addTarget(self, action: #selector(self.openSettings), for: .touchUpInside)
let settingsButton = UIBarButtonItem(customView: profileImageButton)

在大多数设备上,视图具有 40x40 帧。但是,当我在 iPhone 6s 上运行它时,它看起来有点长方形。所以我在 Xcode 的调试层次特性中打印出了它的框架。我得到的结果是:frame = (0 0; 50 44),我假设这意味着框架的尺寸为 50x44。因此,我的问题是为什么 iPhone 6s 不保持指定的 40x40 尺寸?

【问题讨论】:

    标签: ios swift uibutton uibarbuttonitem


    【解决方案1】:

    除了 matt 的回答,我还需要添加这三行代码以在 iOS 11 中使用:

    profileImageButton.translatesAutoresizingMaskIntoConstraints = false
    profileImageButton.heightAnchor.constraint(equalToConstant: 40).isActive = true
    profileImageButton.widthAnchor.constraint(equalToConstant: 40).isActive = true
    

    【讨论】:

      【解决方案2】:

      在 iOS 11 中,带有自定义视图的 UIBarButtonItem 的大小由自定义视图的内部约束决定。你没有提供任何内部约束,所以所有的赌注都没有;您没有让自己负责条形按钮项目的大小。为此,请给profileImageButton 一个宽度约束和一个高度约束。

      【讨论】:

      • 是否只需要设置它的宽度和高度锚点?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 2020-05-29
      • 2011-02-09
      • 2014-11-20
      相关资源
      最近更新 更多