ios - 自定义大小的自定义 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
稍后填充。我想根据标签的高度调整自定义视图的大小。我怎样才能做到这一点?
解决方案
向 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
}
}
推荐阅读
- reactjs - Reactjs.NET - 道具未定义并坚持为什么?
- javascript - 缩小时传单折线精度损失
- javascript - 在 Angular 7 指令中使用承诺?
- webpack - 在 SASS 中导入本地字体文件时,Webpack 构建失败
- python - 导入 numpy.core.numerictypes 时出现 statsmodels 错误:AttributeError: module 'numpy.core' has no attribute 'numerictypes'
- ssas - 总结然后计算与计算然后总结 (SSAS-MDX)
- sql-server - 插入后根据其他表的增量更改插入行列的值的SQL Server触发器?
- regex - $rename MongoDB 字段名称在 mongo shell 中使用 $regex?
- c# - 如何在另一个 UserControl(Container) 中调用 userControl(child)
- java - 在 JList 上设置透明背景