intrinsticContentSize和invalidateIntrinsticContentSize

intrinsticContentSize是自定义UIView子类的固有大小,只要是重写了这个属性的UIView子类(如UILabel,UIButton,UIImageView等),在添加约束时可以只添加位置(position)约束而不添加尺寸(size)约束。但是,这个属性并不完全等于尺寸约束。如果这个属性是动态的,在它改变时,view不会重新layout,即使调用setNeedsLayout()或者layoutSubviews()方法也无法再次触发这个方法。官方的解释有说明这一点:

Custom views typically have content that they display of which the layout system is unaware. Setting this property allows a custom view to communicate to the layout system what size it would like to be based on its content. This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height, for example.

这时我们需要用到invalidateIntrinsticContentSize()方法来停止使用之前的intrinsticContentSize,并根据新的(当前的)intrinsticContentSize来进行尺寸约束。官方也有明确说明:

Call this when something changes in your custom view that invalidates its intrinsic content size. This allows the constraint-based layout system to take the new intrinsic content size into account in its next layout pass.

不得不说的是,invalidateIntrinsticContentSize()这个方法的命名误导性极强,只提及了前半部分功能,而完全没有提到后半部分关于重新约束的功能,在没有阅读文档之前,我还一直在使用setNeedsLayout()layoutSubviews()方法试图重新布局,然而,尺寸约束根本没有改变,无论怎么调用这两个方法也不会有任何事情发生,这是让人十分沮丧的事。

另外,由于intrinsticContentSize是在UIViewController的viewDidLoad()或者LoadView()方法后执行的,对于那些只在这两个方法中初始化并填充自定义view的流程,上面的讨论是没有意义的。这个讨论是针对那些先初始化,再填充的流程的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 写在前面 iOS的的布局机制「auto layout」不是一个新概念,它早在iOS 6中就推出来了,当下距离iOS...
    西门淋雨阅读 1,591评论 2 4
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,997评论 0 23
  • 前情回顾:听他说 第八章 放开那个女孩 十二月二十四日晚11点10分,“天渊”之上,通天之塔。足以照亮整片夜空的金...
    澜夜师兄阅读 557评论 1 19
  • 秋游南山 作者:高英 秋雨生寒意, 黄叶落山坡。 远眺思故园, 近步闻花香。 野菊欲初绽, 柿树果已尝。 身在自然...
    泠风思语阅读 239评论 0 1
  • 文/啊啊啊爬树的人 最励志的一句话就是—— 这个世界上比你还有天赋的人比你更努力,你还如何淡定得下去? 我想先说一...
    啊啊啊爬树的人阅读 490评论 0 1