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)
}
Then call
invalidateIntrinsicContentSize()
Whenever your custom view’s intrinsic content size changes and the frame should be updated.
Notes
- Swift 3 update: Easier Auto Layout: Coding Constraints in iOS 9
- Just because you have the intrinsic content size set up in your custom view doesn’t mean it will work as you expect. Read the documentation for how to use it, paying special attention to Content-Hugging and Compression-Resistance.
- Thanks also to this Q&A for putting me on the right track: How can I add padding to the intrinsic content size of UILabel?
- Thanks also to this article and the documentation for help with
invalidateIntrinsicContentSize().