I have the following structure in my interface builder:
MyCustomView
StackView
Label
TextField
Label - is hidden
Button
When the button is pressed, the logic of the CustomView should make the bottom label appear and so the IntrinsicContentSize be calculated again. Unfortunately the view is presented properly only after the second button click.
Here is the relevant code:
public class MyCustomView: UIView {
...
var subtitle: String! {
didSet {
subtitleLabel.isHidden = subtitle.isEmpty
subtitleLabel.text = subtitle
invalidateIntrinsicContentSize()
}
}
....
override public var intrinsicContentSize: CGSize {
stackView.layoutIfNeeded()
return stackView.bounds.size
}
....
}
The line that I was missing is stackView.setNeedsLayout()
when making one of stackView subviews unhidden.
So this is the working didSet
:
var subtitle: String! {
didSet {
subtitleLabel.isHidden = subtitle.isEmpty
subtitleLabel.text = subtitle
stackView.setNeedsLayout()
invalidateIntrinsicContentSize()
}
}