Peter Lapisu
Peter Lapisu

Reputation: 20965

Autolayout UIImageView without image

I have a UIImageView, with scaling Center, so it's size changes according to the UIImage inside, however, by setting a nil UIImage, the constraints break, as no content size can be calculated

How to handle the autolayout with nil UIImage (the size should be changed to 0,0)?

Upvotes: 5

Views: 3509

Answers (3)

Yevhen Dubinin
Yevhen Dubinin

Reputation: 4733

@nikita-ivaniushchenko's answer gave me an idea to add Width constraint with Low (250) priority equals to 0 to UIImageView, so it is applied when UIImage is set to nil.

Storyboard UIImage Constraints Example

Note: I added Width constraint only, because there was only issue with UIImageView's width in my case. Should work for both, though.

Upvotes: 13

Shmidt
Shmidt

Reputation: 16664

Set Content hugging priority to Required (1000).

Update: This answer was working before, but it doesn't work now. Use Nikita Ivaniushchenko answer instead.

Upvotes: 0

Nikita Ivaniushchenko
Nikita Ivaniushchenko

Reputation: 1435

The problem is that UIImageView returns {-1, -1} as intrinsicContentSize when no image is set. Use subclass of UIImageView with implementation like this:

@implementation MyImageView

- (CGSize)intrinsicContentSize
{
    if (self.image)
    {
        return [super intrinsicContentSize];
    }

    return CGSizeZero;
}

@end

Upvotes: 18

Related Questions