Swift - intrinsicContentSize is not called on time

1k Views Asked by At

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
}

....

}

enter image description here enter image description here

1

There are 1 best solutions below

0
On BEST ANSWER

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()
    }
}