下方的分享图标(图片为白色)为 114x128 像素。
不过,使用 AutoLayout 将 Interface Builder 中的高度固定为 23 像素,然后对 Content Mode 使用 Aspect Fit 不会更改框架矩形。
这会导致对齐问题,因为如果您希望图标距离后缘 15 像素,现在很难做到。
一种选择是在 IB 中手动设置宽高比(即 114/128)作为自动布局约束。
但这非常脆弱。如果更改图像尺寸,则必须记住调整纵横比。
有没有办法让 IB 自动调整框架矩形以及内容?
最后一个选项是在代码中完成所有操作,但在 IB 中完成所有操作将是理想的选择。
框架矩形在 IB 中不变:
分享图标(白色图标所以在这里不可见):
最佳答案
我相信您必须以编程方式执行此操作。如果您不想逐个查看,只需定义一些以编程方式设置约束的子类(您可以将其指定为 IB 中的基类)
class RatioImageView: UIImageView {
private var ratioConstraint: NSLayoutConstraint?
override var image: UIImage? {
didSet { updateRatioConstraint() }
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
updateRatioConstraint()
}
private func updateRatioConstraint() {
if let ratioConstraint = ratioConstraint {
removeConstraint(ratioConstraint)
}
guard superview != nil else { return }
let ratio: CGFloat
if let image = image {
ratio = image.size.width / image.size.height
} else {
ratio = 1
}
ratioConstraint = widthAnchor.constraint(equalTo: heightAnchor, multiplier: ratio)
ratioConstraint?.isActive = true
}
}
这是在 ImageView 上执行的,但您可能也可以对 UIButton
或其他任何内容执行相同的操作。
或者在主题的另一个变体中,您可以使用固有大小来控制它,您可以在其中显式设置 height
(因为这是 @IBInspectable
,您可以在 IB 中正确执行此操作),它将返回针对该高度缩放的固有尺寸:
@IBDesignable
class RatioImageView: UIImageView {
@IBInspectable var height: CGFloat = 0
override var intrinsicContentSize: CGSize {
guard let image = image else { return .zero }
guard height > 0 else { return image.size }
let ratio = image.size.width / image.size.height
return CGSize(width: height * ratio, height: height)
}
}
关于ios - 界面生成器 : automatically set aspect ratio for UIImageView when using "Aspect Fit"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47964843/