简体   繁体   中英

Swift - intrinsicContentSize is not called on time

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM