【问题标题】:tableView heightForRowAtIndexPath Not workingtableView heightForRowAtIndexPath 不工作
【发布时间】:2016-03-10 19:32:13
【问题描述】:

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

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

我搜索了一下,找到了

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

【问题讨论】:

标签: ios swift uitableview


【解决方案1】:

您没有正确实现heightForRowAtIndexPath 方法。你应该阅读self sizing table view cells,因为它会做你想做的事。

基本上,要使用自动调整大小的单元格,对于 UITableView,您将设置估计的行高,并将 rowHeight 设置为值 UITableViewAutomaticDimension(或 Swift 4.2 或更高版本中的 UITableView.automaticDimension)。

在 Swift 4.2 之前:

tableView.estimatedRowHeight = 85.0
tableview.rowHeight = UITableViewAutomaticDimension

Swift 4.2:

tableView.estimatedRowHeight = 85.0
tableView.rowHeight = UITableView.automaticDimension

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

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

如需有关自定尺寸单元的良好指南,请查看this tutorial

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

【讨论】:

  • 我删除了 heightForRowIndexPath 并使用了 self.myTable.estimatedRowHeight = 160 self.myTable.rowHeight = UITableViewAutomaticDimension
  • 您需要确保您的单元格都已使用自动布局正确设置。如果没有正确调整大小,它将无法正常工作。
  • 你的意思是约束?
  • 是的,需要正确设置自动布局约束,以便自动调整大小的单元格知道每个单元格的大小。
猜你喜欢
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
相关资源
最近更新 更多