Search code examples
iosswiftxcodeautolayout

UIImageView auto-created content size auto layout constraints overlap with trailing/leading constraints


I have a UIImageView (it's actually an FLAnimatedImageView). I use auto layout to set its constraints to occupy the entire screen. This works well in iPhone, but in iPad the auto-created constraints of the content (shown in the picture) cause it to take only some of the screen's size.

I don't understand why are these constraints created, and if they are indeed needed, why aren't the complying to the trailing/leading constraints?

constraints

The image only taking some of the screen's size


Solution

  • I've googled the source of your view and found it at GitHub. After looking into the implementation I found following code fragment:

    - (CGSize)intrinsicContentSize
    {
        // Default to let UIImageView handle the sizing of its image, and anything else it might consider.
        CGSize intrinsicContentSize = [super intrinsicContentSize];
    
        // If we have have an animated image, use its image size.
        // UIImageView's intrinsic content size seems to be the size of its image. The obvious approach, simply calling `-invalidateIntrinsicContentSize` when setting an animated image, results in UIImageView steadfastly returning `{UIViewNoIntrinsicMetric, UIViewNoIntrinsicMetric}` for its intrinsicContentSize.
        // (Perhaps UIImageView bypasses its `-image` getter in its implementation of `-intrinsicContentSize`, as `-image` is not called after calling `-invalidateIntrinsicContentSize`.)
        if (self.animatedImage) {
            intrinsicContentSize = self.image.size;
        }
    
        return intrinsicContentSize;
    }
    

    It seems that in case of animatedImage the size will be reduced to the original image size.

    The apple documentation tells about intrinsic content size:

    In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need

    This can be interpreted as intrinsic content size usage already adds size constraints. For more informations about intrinsic content size usage see: Apple Documentation

    One solution might be (not sure if there are some side effects) to use a subclass that overrides intrinsic content size like that:

    override var intrinsicContentSize: CGSize {
        return CGSize(width: UIViewNoIntrinsicMetric, height: UIViewNoIntrinsicMetric)
    }
    

    BTW: Please provide a link to the sources in next questions, it save us time searching for it. Thanks!