With Auto Layout, how do I make a UIImageView's size dynamic depending on the image?

后端 未结 8 475
花落未央
花落未央 2020-11-28 21:57

I want my UIImageView to grow or shrink depending on the size of what the actual image it\'s displaying is. But I want it to stay vertically centered and 10pts

8条回答
  •  春和景丽
    2020-11-28 22:15

    I usually add no image height and width constraints with value 0 and priority less than UIImageView's contentCompressionResistancePriority, which by default is 750. These two constraints will activate only when there is no image, and will take care of ambiguous constraints warnings both at run time and compile time.

    Pretty straight forward to add these in IB. Programatically, it should look something like below.

    let noImageWidthConstraint = imageview.widthAnchor.constraint(equalToConstant: 0)
    noImageWidthConstraint.priority = UILayoutPriority(rawValue: 100)
    noImageWidthConstraint.isActive = true
    
    let noImageHeightConstraint = imageview.heightAnchor.constraint(equalToConstant: 0)
    noImageHeightConstraint.priority = UILayoutPriority(rawValue: 100)
    noImageHeightConstraint.isActive = true
    

提交回复
热议问题