我在實作UITableView的自動單元格大小時遇到了困難。我試圖使用一個UIStackView,其單元格內有2個標簽,并具有自動大小。
而它使用的單元格: uj5u.com熱心網友回復: 之所以會出現模糊的高度,是因為兩個標簽都有相同的內容擁抱優先級。
自動布局做出了它的 "最佳猜測",你得到了想要的輸出 -- 但你仍然會在除錯視圖層次中看到這些問題。
為了擺脫它,你可以給一個標簽一個更高的擁抱優先級。
例如(在
標籤:
class ViewController: UIViewController {
struct CellData {
let title: String[/span]。
let subtitle: String
}
let table = UITableView()
let data = [
CellData(標題。"Foo"/span>, subtitle: "Bar")。)
CellData(標題。"Baz", subtitle: "FooBar")
]
private let cellReuseID = "CellReuseID"
override func viewDidLoad() {
super.viewDidLoad()
table.register(Cell.self, forCellReuseIdentifier: cellReuseID)
table.dataSource = self
table.rowHeight = UITableView.automaticDimension
table.tableFooterView = UIView(frame: .zero)
table.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(table)
NSLayoutConstraint.activated([
table.leadingAnchor.constraint(equalTo: view.leadingAnchor)。
table.trailingAnchor.constraint(equalTo: view.trailingAnchor)。
table.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor)。
table.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)。
])
}
}
extension ViewController。UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView. dequeueReusableCell(withIdentifier: cellReuseID) as? Cell else {
fatalError()
}
cell.title = data[indexPath.row].title
cell.subtitle = data[indexPath.row].subtitle
return cell。
}
}
class Cell: UITableViewCell {
var title: String? {
didSet {
titleLabel.text = title
}
}
var subtitle: String? {
didSet {
subtitleLabel.text = subtitle
}
}
let titleLabel = UILabel()
let subtitleLabel = UILabel()
override init(style: UITableViewCell.CellStyle, reuseIdentifier。String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented"/span>)
}
private func setupView() {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .top
stackView.分布 = .fill
stackView.spacing = 8
stackView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(stackView)
NSLayoutConstraint.activated([
stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor)。
stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor)。
stackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)。
stackView.topAnchor.constraint(equalTo: contentView.topAnchor)
])
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(subtitleLabel)
}
}
setupView()中): titleLabel。 setContentHuggingPriority(.defaultHigh 1, for: .vertical)
subtitleLabel.setContentHuggingPriority( .defaultHigh, for: .vertical)


