heightForRowAtIndexPath
并使用下面所示的代码获取UILabel
所需的大小。然而,此方法在调用cellForRowAtIndexPath
之前被调用,因此我无法根据单元格中的内容进行调整大小,这对我来说似乎是一个非常奇怪的选择。基于内容动态调整单元格高度的“最佳实践”是什么?此外,为什么苹果没有让
heightForRowAtIndexPath
方法在cellForRowAtIndexPath
之后调用?我在
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 的框架变成大于 tableview.rowHeight,则它将不会显示。因此,需要在每个单元格的基础上从 heightForRowAtIndexPath(我假设)重新调整行高。
heightForRowAtIndexPath
方法完全独立于cellForRowAtIndexPath
方法的调用。在需要显示当前可见的少数单元格之前,表视图需要提前知道其完整的高度。 - rmaddytableView:heightForRowAtIndexPath:
方法中的当前代码是什么?你是否看过以下答案:https://dev59.com/MGIj5IYBdhLWcg3wnmXA,https://dev59.com/1l8e5IYBdhLWcg3w9-Rs,https://dev59.com/o14c5IYBdhLWcg3w7t_E? - Robotic Cat