如何在Swift中设置自定义视图的内在内容大小? [英] How to set a custom view's intrinsic content size in Swift?
问题描述
背景
我正在制作一个垂直标签,用于传统的蒙古文字。在我刚刚轮换 UILabel
之前,但是存在一些性能问题和其他复杂问题。现在我正在努力从头开始制作标签。但是,我需要垂直标签在高度调整时告诉自动布局(基于字符串长度)。
I am making a vertical label to use with traditional Mongolian script. Before I was just rotating a UILabel
but there were some performance issues and other complications with this. Now I am working on making a label from scratch. However, I need the vertical label to tell auto layout when its height adjusts (based on string length).
我读过的内容
我读了内在内容大小和具有内在内容大小的视图文档。这些更多是关于如何使用它,而不是如何在自定义视图中定义它。
I read the Intrinsic Content Size and Views with Intrinsic Content Size documentation. These were more about how to use it, though, and not how to define it in a custom view.
仅搜索自定义视图的ios内在大小给了我
Searching for "ios intrinsic content size for a custom view" only gives me
- Proper usage of intrinsicContentSize and sizeThatFits: on UIView Subclass with autolayout
。这个特殊问题甚至不需要内在的内容大小,因为他们的视图只是标准视图的集合。
in Stack Overflow. This particular question didn't even need intrinsic content size because their view was just an assembly of standard views.
我正在尝试
我正在尝试的是下面的答案。我正在添加这个Q& A对,这样就不会花费其他人那么长的时间来找到答案,因为它使用了我使用的搜索关键字。
What I am trying is my answer below. I am adding this Q&A pair so that it won't take other people as long to find the answer as it took me with the search keywords that I used.
推荐答案
设置自定义视图的内在内容大小可让自动布局知道该视图的大小。为了设置它,你需要覆盖 intrinsicContentSize
。
Setting the intrinsic content size of a custom view lets auto layout know how big that view would like to be. In order to set it, you need to override intrinsicContentSize
.
override var intrinsicContentSize: CGSize {
return CGSize(width: x, height: y)
}
然后致电
invalidateIntrinsicContentSize()
每当您的自定义视图的内在内容大小发生变化且帧应该更新时。
Whenever your custom view's intrinsic content size changes and the frame should be updated.
注释
-
Swift 3更新:更简单的自动布局:iOS 9中的编码约束
阅读使用Swift和自动布局编写适用于iOS 8的自定义控件,以获取如何在上下文中正确完成此操作的示例。
Read Writing a Custom Control for iOS 8 using Swift and Auto Layout for an example of how this is done correctly in context.
这篇关于如何在Swift中设置自定义视图的内在内容大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!