首页 > 解决方案 > 自定义大小的自定义 UIView

问题描述

我正在尝试UIView根据以下内容计算自定义的高度UIStackView

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

nameLabel和的内容descriptionLabel稍后填充。我想根据标签的高度调整自定义视图的大小。我怎样才能做到这一点?

标签: iosswift

解决方案


向 stackView 添加约束并将translatesAutoresizingMaskIntoConstraints属性设置为 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
}
}

推荐阅读