2017-10-21 88 views
0

設置我UIImageView這樣的:的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。怎麼樣?至少控制檯應打印它打破一些限制?

參見 「調試視圖層次」 的樣子:enter image description here

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

我試過兩個軸系設置profileImage.setContentHuggingPriority()至1000,但不工作。

我試圖返回在intristicContentSize 140x140爲UIImageView,不過沒有關係,它仍然是325x325(但說140 (content size)

我試過.scaleAspectFit而不是.scaleAspectFill

我只是疑惑

完全公開,這裏的RoundImageView

class RoundImageView: UIImageView { 

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

} 
+0

此代碼位於何處?什麼是「自我」? - 我只是試過你的代碼,它完美的工作;除了我必須在'addSubview'和'topAnchor'之前添加'self.view.',這讓我相信你在另一個UIView子類中這樣做,這可能會影響最終結果。 – Paulw11

+0

@ Paulw11謝謝你的努力。我已經解決了它。當我想着如何向你解釋時,它讓我想到了。並在一個地方找到了'profileImage.sizeToFit()'這一行 - 這似乎是它造成的。事情是,它會爲我第一次正確地佈局 - 但第二次我會查看它,圖像會被拉長。 – netigger

回答

0

我找到了答案。在一個地方 - 我更新了視圖,我有profileImage.sizeToFit(),它使所有約束保持不變,但圖像變大了。

左側圖像是第一個佈局 - 第二個在UIImageView中調用sizeToFit之後。

enter image description hereenter image description here