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