简体   繁体   English

Swift - 未按时调用 intrinsicContentSize

[英]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.当按下按钮时,CustomView 的逻辑应该使底部的 label 出现,因此再次计算 IntrinsicContentSize。 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.在取消隐藏 stackView 子视图之一时,我缺少的行是stackView.setNeedsLayout()

So this is the working didSet :所以这是工作didSet

var subtitle: String! {
    didSet {
        subtitleLabel.isHidden = subtitle.isEmpty
        subtitleLabel.text = subtitle
        stackView.setNeedsLayout()
        invalidateIntrinsicContentSize()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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