我有一个表格 View ,其中每个单元格显示一个可选标题和一个多行副标题。我希望单元格能够自动调整大小(即随着字幕一起增长,但尽可能保持紧凑)。为此,我使用 tableView.rowHeight = UITableView.automaticDimension
我遇到的问题是,在有标题的单元格中,副标题周围有相当多的垂直间距。
没有标题的单元格已正确压缩。另外,当我重新加载表格 View 时,所有布局都会变得正确。
预期行为:
实际行为:
单元格基本上有一个固定到单元格的 contentView
的 UIStackView
。
import UIKit
public class TableViewCellSubtitle: UITableViewCell {
private lazy var labelStack: UIStackView = {
let labelStack = UIStackView()
labelStack.alignment = .fill
labelStack.distribution = .fillProportionally
labelStack.axis = .vertical
return labelStack
}()
private lazy var titleLabel: UILabel = {
let titleLabel = UILabel()
titleLabel.backgroundColor = UIColor.blue.withAlphaComponent(0.3)
return titleLabel
}()
private lazy var subtitleLabel: UILabel = {
let subtitleLabel = UILabel()
subtitleLabel.numberOfLines = 0
subtitleLabel.backgroundColor = UIColor.green.withAlphaComponent(0.3)
return subtitleLabel
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
contentView.addSubview(labelStack)
labelStack.translatesAutoresizingMaskIntoConstraints = false
labelStack.addArrangedSubview(titleLabel)
labelStack.addArrangedSubview(subtitleLabel)
}
private func setupConstraints() {
NSLayoutConstraint.activate([
labelStack.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
labelStack.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
contentView.bottomAnchor.constraint(equalTo: labelStack.bottomAnchor, constant: 12),
contentView.trailingAnchor.constraint(equalTo: labelStack.trailingAnchor, constant: 16)
])
}
public func setup(title: String?, subtitle: String) {
titleLabel.text = title
if title == nil {
labelStack.removeArrangedSubview(titleLabel)
titleLabel.removeFromSuperview()
}
subtitleLabel.text = subtitle
}
}
我尝试在字幕上设置内容拥抱
subtitleLabel.setContentHuggingPriority(.required, for: .vertical)
但这使得标题变得更大:
如果我将其设置为两者:
titleLabel.setContentHuggingPriority(.required, for: .vertical)
subtitleLabel.setContentHuggingPriority(.required, for: .vertical)
变成了
在所有情况下,如果我重新加载单元格或表格 View ,布局就会变得正确(此处为单元格点击):
我知道我可以在不使用堆栈 View 的情况下布局单元格,但我的实际实现有点复杂
最佳答案
- 尝试使用填充而不是按比例填充
- 或者尝试设置 label.sizeToFit() 将标签折叠到其内容大小
关于swift - UITableViewCell 中带有多行标签的 UIStackView 高度不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56166371/