请稍侯

uistackview 问题 在

03 August 2023

UIStackView 问题

在使用 UIStackView 时,它会根据子视图的 intrinsic content size 自动调整高度,而不是根据约束进行调整。

class DynamicHeightLabel: UILabel {
    override var intrinsicContentSize: CGSize {
        let maxSize = CGSize(width: bounds.width, height: .greatestFiniteMagnitude)
        let textRect = super.textRect(forBounds: bounds, limitedToNumberOfLines: numberOfLines)

        return CGSize(width: bounds.width, height: ceil(textRect.height))
    }
}

let label = DynamicHeightLabel()
label.numberOfLines = 3
label.text = "这是一段带有\n换行的\n文本内容的例子。"

containerView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
    label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
    label.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
    label.topAnchor.constraint(equalTo: containerView.topAnchor),
    label.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
])

// 更新 UIStackView 的布局
stackView.layoutIfNeeded()

//调用 stackView.layoutIfNeeded() 方法,以确保 UIStackView 根据子视图的 intrinsic content size 进行调整。