【问题标题】:UIImageView auto-created content size auto layout constraints overlap with trailing/leading constraintsUIImageView 自动创建的内容大小自动布局约束与尾随/前导约束重叠
【发布时间】:2017-04-19 14:08:43
【问题描述】:

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

我不明白为什么要创建这些约束,如果确实需要它们,为什么不遵守尾随/前导约束?

【问题讨论】:

    标签: ios swift xcode autolayout


    【解决方案1】:

    我已经在 Google 上搜索了您的观点的来源,并在 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;
    }
    

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

    苹果文档讲述了内在内容大小:

    一般来说,内在内容大小简化了布局,减少了您需要的约束数量

    这可以解释为内在内容大小的使用已经增加了大小限制。有关内在内容大小使用的更多信息,请参阅:Apple Documentation

    一种解决方案可能是(不确定是否有一些副作用)使用覆盖内部内容大小的子类,如下所示:

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

    顺便说一句:请在下一个问题中提供指向来源的链接,这样可以节省我们搜索它的时间。谢谢!

    【讨论】:

      【解决方案2】:

      虽然接受的答案确实为不创建这些自动约束提供了解决方案,但导致我的视​​图被剪切的问题却不同。

      我在viewDidLoad 中进行视图设置(不是通过情节提要),但视图边界更改不会生效。

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

      来自viewDidLayoutSubviews官方文档:

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

      来源:Apple Docs

      【讨论】:

        猜你喜欢
        • 2015-04-02
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        • 2015-08-02
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多