[英]Changing UITableViewCell height depending on size of UILabel subview
我正在制作一个简单的短信应用程序进行练习,UITableView有很多包含消息的单元格。
它适用于单行消息,但是,如您在底部所看到的,对于多行文本,UITableViewCell的大小开始妨碍并缩短消息。 以防万一,这是我的cellForRowAtIndexPath方法的代码:
internal func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if usernames[indexPath.row] == PFUser.currentUser()?.username {
cell = tableView.dequeueReusableCellWithIdentifier("text")!
} else {
cell = tableView.dequeueReusableCellWithIdentifier("reply")!
(cell.viewWithTag(2) as! UILabel).text = usernames[indexPath.row]
}
(cell.viewWithTag(1) as! UILabel).text = messages[indexPath.row]
return cell
}
基本上,我只需要一个解决方案即可使该应用程序支持多行消息。 在此先感谢您的帮助!
您需要做的两件事:
1)在viewDidLoad
,指定以下内容:
tableView.rowHeight = UITableViewAutomaticDimension
# The estimated row height number is not that important, just approximate it
tableView.estimatedRowHeight = 140
2)为您的自定义单元格定义所有约束。 确保明确定义了顶部和底部约束。
第二步特别重要。
1)在情节提要中,在“属性检查器”部分中。 设定线= 0
2)在func viewDidLoad()中,
tableView.estimatedRowHeight = 50.0
tableView.rowHeight = UITableViewAutomaticDimension
您可以使用自动调整大小的表格视图单元格和UITableViewAutomaticDimension
。 这是一篇很好的文章。
使自动布局可在UITableViewCell上工作的技巧是确保您具有约束所有子视图的约束,即每个子视图应具有前导,顶部,尾部和底部约束。 然后,子视图的固有高度将用于指示每个单元格的高度。 您现在就要做。
然后将rowHeight设置为UITableViewAutomaticDimension
:
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.