【发布时间】:2016-04-06 18:29:28
【问题描述】:
我正在尝试创建一个 UITableView,其单元格的高度根据显示的文本量来调整大小。这看起来很简单,因为heightForRowAtIndexPath 可用,我可以使用下面显示的代码获得UILabel 所需的大小。但是,这种方法被称为 before cellForRowAtIndexPath 所以我不能根据单元格中的内容调整大小,这对我来说似乎是一个非常奇怪的选择。根据内容动态调整单元格高度的“最佳实践”方法是什么?
另外,为什么Apple没有在cellForRowAtIndexPath之后调用heightForRowAtIndexPath方法?
我在cellForRowAtIndexPath 中使用以下内容来确定我的标签所需的高度,但我不确定如何将其移至heightForRowAtIndexPath,因为无法在该方法中调用dequeReusableCellWithIdentifier(就我而言知道):
func getRequiredLabelHeight(label: UILabel, text: String, font: UIFont) -> CGFloat {
label.numberOfLines = 0
label.lineBreakMode = .ByWordWrapping
label.font = font
label.text = text
label.sizeToFit()
return label.frame.height
}
我也知道我希望以下是我的单元格高度,因为我希望单元格大小根据新标签大小(可以是任意长度)从初始大小(铰接在 1 行标签上)增加行数)
self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height
谢谢!
编辑
我的问题与调整标签大小无关。我提供的代码就是这样做的。问题是单元高度不是恒定的。它根据内容在整个表格中有所不同,因此我不能使用静态tableview.rowHeight。由于我无法从cellForRowAtIndexPath 调整单元格高度,因此我的内容将不适合单元格。例如,这是我的cellForRowAtIndexPath(简而言之):
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let commentCell: CommentTableViewCell = tableView.dequeueReusableCellWithIdentifier("commentTableViewCell", forIndexPath: indexPath)
as! CommentTableViewCell
commentCell.commentTextLabel.textColor = Utils.hatchliTextDark
commentCell.commentTextLabel.font = UIFont(name: "Avenir", size: 16)
self.cellHeight = getRequiredLabelHeight(commentCell.commentTextLabel, text: allComments![indexPath.row].text, font: UIFont(name: "Avenir", size: 16.0)!) + commentCell.bounds.height - commentCell.commentTextLabel.bounds.height
commentCell.commentTextLabel.frame = CGRectMake(commentCell.commentTextLabel.frame.origin.x, commentCell.commentTextLabel.frame.origin.y, commentCell.commentTextLabel.frame.width, self.cellHeight)
commentCell.handleTextLabel.text = String(allComments![indexPath.row].creatorHandle)
commentCell.votesTextLabel.text = String(allComments![indexPath.row].votes)
commentCell.commentTextLabel.text = allComments![indexPath.row].text
commentCell.setMargin()
return commentCell
}
所以,如果UILabel的frame变大than tableview.rowHeight,就不会出现了。因此,行高需要从heightForRowAtIndexPath(我假设)基于每个单元格调整大小
【问题讨论】:
-
heightForRowAtIndexPath的调用完全独立于cellForRowAtIndexPath。表格视图需要知道它的完整高度,然后才需要显示此时恰好可见的少数单元格。 -
您是否使用自动调整单元格大小的自动布局?如果不是,您的
tableView:heightForRowAtIndexPath:方法中的当前代码是什么?您是否看过类似以下的答案:stackoverflow.com/q/20068849/558933、stackoverflow.com/q/25180443/558933、stackoverflow.com/q/27374612/558933 -
可以在每个单元格的基础上自动调整 UITableView 的单元格高度吗?
标签: ios swift uitableview