tableView heightForRowAtIndexPath不起作用

时间:2016-03-10 19:32:13

标签: ios swift uitableview

我有表格视图来显示用户的评论

我需要根据内容高度使每行的高度动态

我搜索了它,然后我找到了

  

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;
}

1 个答案:

答案 0 :(得分:5)

您尚未正确实施heightForRowAtIndexPath方法。你应该阅读self sizing table view cells因为它会做你想做的事情。

基本上,要使用自定义单元格,对于UITableView,您将设置估计的行高,并将rowHeight设置为值UITableViewAutomaticDimension

tableView.estimatedRowHeight = 85.0
tableview.rowHeight = UITableViewAutomaticDimension` 

将估计行高度值设置为与所有单元格的粗略平均高度非常接近的值。这有助于iOS了解完整UIScrollView内容的大小。

此外,对于自定义单元格,您根本不会实现heightForRowAtIndexPath。每个单元格高度都是从每个单元格内的约束中获得的。

有关自我调整单元格的详细指南,请查看this tutorial

如果您不想自定义单元格,可以实现heightForRowAtIndexPath,但需要为每个单元格返回正确的高度。该逻辑将取决于您根据indexPath参数确定。但是你需要确保返回每个单元格的高度(由indexPath指定),以像素为单位(逻辑像素)。

相关问题