【发布时间】:2021-03-08 06:30:02
【问题描述】:
我希望我的UITableViewCell 正确计算其高度,使其底部与UIStackView 底部匹配。
我知道要使UITableView.automaticDimension 工作,您需要设置UITableViewCell 的所有垂直约束,以便它可以计算其高度。
这就是我做不到的。我做了一个测试项目,我确定:
-
tableView.rowHeight属性设置为UITableView.automaticDimension。 - 不实现函数
heightForRowAt。 -
TableViewCellRow Height在 xib 文件中设置为Automatic。 - 所有视图都受到垂直约束。
- 玩
UIStackViewdistribution属性。 - 要将
UIStackView底部约束设置为superView到Less Than or Equal(此项目太小并且Greater Than or Equal或Equal,项目的高度等于屏幕宽度,因为它们有@987654344 @ 1:1 - 与
Content Hugging Priority和Content Compression Resistance Priority一起玩。在测试中,所有视图都有默认值,水平和垂直拥抱为 250,水平和垂直压缩为 750。
代码:
import Foundation
import UIKit
class IBAutomaticDimensionTableViewViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet private weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.register(
IBAutomaticDimensionTableViewCell.nib,
forCellReuseIdentifier: IBAutomaticDimensionTableViewCell.nibName
)
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
// view.layoutIfNeeded() Not working with or without it
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(
withIdentifier: IBAutomaticDimensionTableViewCell.nibName,
for: indexPath
) as! IBAutomaticDimensionTableViewCell
return cell
}
}
Less Than or Equal 底部约束的结果:
带有Greater Than or Equal 或Equal 底部约束的结果:
【问题讨论】:
标签: swift uitableview storyboard uistackview uitableviewautomaticdimension