我有表格视图来显示用户的评论。
我需要根据内容高度使每一行的高度动态。
我搜索了它,我发现
heightForRowAtIndexPath法
但它不起作用,否则我不知道怎么用它!
这是我的密码:
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
let username = cell.viewWithTag(1) as! UILabel
let comment = cell.viewWithTag(2) as! UITextView
username.text = usernames[indexPath.row]
comment.text = comments[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.comments.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}发布于 2016-03-10 20:25:01
您没有正确实现heightForRowAtIndexPath方法。你应该阅读自定尺寸表视图单元格,因为它会做你想做的事情。
基本上,要使用自调整大小的单元格,您将为UITableView设置一个估计行高,并将rowHeight设置为UITableViewAutomaticDimension值(或者SWIFT4.2或更高版本中的UITableView.automaticDimension )。
Swift 4.2之前的:
tableView.estimatedRowHeight = 85.0
tableview.rowHeight = UITableViewAutomaticDimensionSwift 4.2:
tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableView.automaticDimension将估计的行高值设置为接近所有单元格的粗平均高度的值。这有助于iOS了解完整的UIScrollView内容有多大。
此外,对于自调整大小的单元格,您将根本不实现heightForRowAtIndexPath。每个单元的高度都是从每个单元内的约束中获得的。
要获得关于自调整大小单元格的良好指南,请查看本教程。
如果不想进行自调整大小的单元格,可以实现heightForRowAtIndexPath,但需要返回每个单元格的正确高度。这个逻辑将由您根据indexPath参数来确定。但您需要确保以像素(逻辑像素)为单位返回每个单元格(由indexPath指定)的高度。
https://stackoverflow.com/questions/35925574
复制相似问题