我在我的Swift项目中有一个这样的表
var tableView: UITableView!
tableView = UITableView()
tableView.dataSource = self
tableView.delegate = self
tableView.rowHeight = UITableViewAutomaticDimension
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postTexts.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 250;
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 5
}我希望我的表视图的高度是自动的,所以我使用了UITableViewAutomaticDimension,但它仍然显示了将近一半的单元宽度

发布于 2017-03-23 16:43:45
您需要内部单元格大小才能正常工作。完全删除heightForRowAt。单元格中的约束应该决定单元格的大小,这意味着您的约束至少应该从上到下固定。在设置rowHeight之后添加以下代码
tableView.estimatedRowHeight = 250发布于 2017-03-23 16:53:31
您必须删除-heightForRow方法并在表视图上设置estimatedRowHeight。
estimatedRowHeight用于计算TV的条形尺寸等,因此它应该是一个实值,尽可能接近表格视图单元格高度的平均大小。
现在,如果您使用的是自动布局,并且约束设置正确,您应该会看到UITableViewCell的大小调整正确。要在TVC中正确设置约束,您应该考虑将它们放置在可以控制单元大小的方式中。
例如,假设您的TVC只有一个标签,而该标签有4个附加到其superview的约束:顶部、底部、尾部和前导,大小固定不变。UILabel实例还将numberOfLines设置为0(这意味着它可以展开以填充所有文本)。
当自动布局引擎开始请求标签intrinsicContentSize时,标签将返回一个适合您所有文本的值,superview大小将根据该值更改大小。
如果您像以前一样将TVC设置为特定的高度,TVC将无法自行扩展。
发布于 2017-03-23 17:45:32
我遇到了约束方面的问题,所以这是我所做的。
首先我添加了heightForRowAt
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}然后我创建了一个变量
let tableViewHeight = postTexts.count*100把它放到我的身高限制中
tableView.anchor(PostsDiv.bottomAnchor, left:view.leftAnchor, bottom: nil, right: view.rightAnchor, topConstant: 40, leftConstant: 15, bottomConstant: 0, rightConstant: 15, widthConstant: 0,heightConstant: CGFloat(tableViewHeight))它对我来说工作得很好
https://stackoverflow.com/questions/42970655
复制相似问题