【问题标题】:UIImageView doesn't respect autolayoutUIImageView 不尊重自动布局
【发布时间】:2018-04-02 18:27:15
【问题描述】:

我这样设置我的UIImageView

let imageSize: CGFloat = 140
let profileImage = RoundImageView()
profileImage.image = UIImage(named: "girl_0")
profileImage.clipsToBounds = true
profileImage.translatesAutoresizingMaskIntoConstraints = false
profileImage.contentMode = .scaleAspectFill
profileImage.layer.masksToBounds = true
profileImage.layer.borderColor = UIColor.GSBackground().cgColor
profileImage.layer.borderWidth = 4.0

addSubview(profileImage)

profileImage.topAnchor.constraint(equalTo: topAnchor, constant: 18).isActive = true
profileImage.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
profileImage.heightAnchor.constraint(equalToConstant: imageSize).isActive = true
profileImage.widthAnchor.constraint(equalToConstant: imageSize).isActive = true

它变为 325x325 而不是 140x140。如何?至少控制台应该打印它打破了一些约束?

查看“调试视图层次结构”的外观:

<...RoundImageView: 0x11903e470; baseClass = UIImageView; frame = (117.5 18; 325 325); clipsToBounds = YES; opaque = NO; userInteractionEnabled = NO; layer = <CALayer: 0x1d023a700>>

我尝试将两个轴的 profileImage.setContentHuggingPriority() 设置为 1000,但不起作用。

我尝试在 intristicContentSize 中为 UIImageView 返回 140x140,但没关系,它仍然是 325x325(但要说 140 (content size)

我试过.scaleAspectFit 而不是.scaleAspectFill

我只是感到困惑。

如需全面披露,请联系RoundImageView

class RoundImageView: UIImageView {

  override func layoutSubviews() {
    super.layoutSubviews()
    layer.masksToBounds = true
    layer.cornerRadius = frame.width / 2
  }

}

【问题讨论】:

  • 这段代码在哪里? self 是什么? - 我刚刚尝试了您的代码,它运行良好;除了我必须在addSubviewtopAnchor 之类的前面添加self.view.,这让我相信你是在另一个 UIView 子类中执行此操作,这可能会影响最终结果。
  • @Paulw11 感谢您的努力。我其实已经解决了。当我在想如何再次向你解释时,它让我思考。并在一个地方找到了“profileImage.sizeToFit()”这一行——这似乎是造成它的原因。问题是,它第一次对我来说也总是正确布局 - 但第二次查看它时,图像会被拉伸。

标签: ios uiimageview autolayout


【解决方案1】:

我找到了答案。在一个地方 - 我更新了视图,我有 profileImage.sizeToFit(),这使得所有约束都保持不变,但图像变得更大。

左图是第一个布局 - 在UIImageView 中调用sizeToFit 之后的第二个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-11
    • 1970-01-01
    相关资源
    最近更新 更多