Ios 自定义UIView的自调整大小

Ios 自定义UIView的自调整大小,ios,swift,Ios,Swift,我正试图根据我的UIStackView的内容计算自定义UIView的高度: class CustomView: UIView { let nameLabel = UILabel() let descriptionLabel = UILabel() let stackView = UIStackView() init() { super.init(frame: .zero) nameLabel.numberOfLines = 0 descriptionL

我正试图根据我的
UIStackView
的内容计算自定义
UIView
的高度:

class CustomView: UIView {
  let nameLabel = UILabel()
  let descriptionLabel = UILabel()

  let stackView = UIStackView()

  init() {
    super.init(frame: .zero)
    nameLabel.numberOfLines = 0
    descriptionLabel.numberOfLines = 0
    stackView.addArrangedSubviews([nameLabel, descriptionLabel])
    stackView.axis = .vertical
    addSubview(stackView)
    // constrain stack view to four sides

    widthAnchor.constrain(to: 100) // hold width 
  }

  func updateText(name: String, description: String) {
    nameLabel.text = name
    descriptionLabel.text = description
    // resize custom view to fit text in nameLabel / descriptionLabel
  }
}

namelab
descriptionLabel
的内容将在以后填充。我想根据标签的高度调整自定义视图的大小。如何实现这一点?

将约束添加到stackView,并将TranslatesAutoResizengMaskinToConstraints属性设置为false

class CustomView: UIView {
let nameLabel = UILabel()
let descriptionLabel = UILabel()

let stackView = UIStackView()

init() {
    super.init(frame: .zero)
    nameLabel.numberOfLines = 0
    descriptionLabel.numberOfLines = 0
    stackView.addArrangedSubview(nameLabel)
    stackView.addArrangedSubview(descriptionLabel)
    stackView.axis = .vertical
    stackView.distribution = .fillProportionally
    addSubview(stackView)
    
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 0.0).isActive = true
    stackView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: 0.0).isActive = true
    stackView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0.0).isActive = true
    stackView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0.0).isActive = true
    // constrain stack view to four sides
    
    // hold width
    translatesAutoresizingMaskIntoConstraints = false
    widthAnchor.constraint(equalToConstant: 100).isActive = true
 
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func updateText(name: String, description: String) {
    nameLabel.text = name
    descriptionLabel.text = description
    // resize custom view to fit text in nameLabel / descriptionLabel
}
}

self.stackview.distribution=.filly
应考虑排列视图的大小