UIImageView自动创建的内容大小自动布局约束与尾随/前导约束重叠

时间:2017-04-19 14:08:44

标签: ios swift xcode autolayout

我有一个UIImageView(它实际上是一个FLAnimatedImageView)。我使用自动布局来设置其约束以占据整个屏幕。这适用于iPhone,但在iPad中,内容的自动创建约束(如图所示)导致它只占用屏幕的一些大小。

我不明白为什么会产生这些约束,如果确实需要这些约束,为什么不遵守尾随/超前约束呢?

constraints

The image only taking some of the screen's size

2 个答案:

答案 0 :(得分:2)

我已经搜索了您的观点来源,并在GitHub找到了它。 在查看实现后,我发现了以下代码片段:

- (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;
}

似乎在animatedImage的情况下,大小将减小到原始图像大小。

Apple文档讲述了内在的内容大小:

  

通常,内在内容大小简化了布局,减少了您需要的约束数量

这可以解释为内在内容大小使用已添加大小约束。有关内在内容大小使用的更多信息,请参阅:Apple Documentation

一个解决方案可能是(不确定是否存在一些副作用)来使用覆盖内在内容大小的子类:

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

BTW:请在下一个问题中提供相关来源的链接,这样可以节省我们搜索它的时间。谢谢!

答案 1 :(得分:0)

虽然接受的答案确实为不能创建这些自动约束提供了解决方案,但导致我的观点被削减的问题却是不同的。

我正在viewDidLoad中进行视图设置(不是通过故事板),但视图边界更改不会生效。

viewDidLayoutSubviews中实现该逻辑(例如,在图像视图中心添加依赖于图像视图宽度的进度条等视图)给了我一个入口点,其中约束生效,因此在此时正确报告UIImageView宽度frame.size.width

来自viewDidLayoutSubviews官方文档:

  

当视图控制器视图的边界发生变化时,视图会调整其子视图的位置,然后系统会调用此方法

来源:Apple Docs