自动调整uitableviewcell – SWIFT
我正在尝试resize的UILabel,可以是一个或多个行的tableviewcell。 我需要为应用程序的其余部分打开自动布局,所以我不想closures它来实现这个工作。 目标是iOS 7和iOS 8。
我已经尝试了几种解决scheme,但由于某种原因,我似乎无法获得标签的正确高度来自动调整或调整单元格高度。
问题发生在这个方法中:calculateHeightForConfiguredSizingCell。 我已经在Git上做了一个示例项目,所以你可以看到我所看到的。
https://github.com/mdaymond/cellResizer
这个例子是基于这篇文章: http : //www.raywenderlich.com/73602/dynamic-table-view-cell-height-auto-layout
更新我检查了代码的更新。 它几乎是以我想要的方式工作,并以编程方式进行计算,但由于某些原因,标签高度的大小并不正确 – 它没有达到所需的全部高度。 原始代码的问题是标签需要明确的宽度。
在这里,如果你支持IOS 7,那么你需要在你的类中实现UITableViewDelegate
协议,然后覆盖:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { }
有关基于标签文本长度的dynamic自定义UITableViewCell高度的更多信息(请参阅heightForRowAtIndexPath
),并且可以将代码放置在heightForRowAtIndexPath
函数中: 基于标签文本长度的高度
还可以覆盖:
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // example to return the estimated height return 280 }
注意 :通过支持IOS 7,你应该手动处理它。 IOS 8没有这么简单的方法。
但是,如果你只支持IOS 8和更高版本,那么你可以简单地在以下两行:
self.tableView.estimatedRowHeight = 280 self.tableView.rowHeight = UITableViewAutomaticDimension
其实我已经下载你的源代码,并做了以下更改。 而UILabel
现在支持multiline
。
第1步:以编程方式删除计算行高。 这意味着在演示中注释了heightForRowAtIndexPath
。
第2步:在UITableViewCell
设置UILabel
布局约束。
第3步:在xib中将行数设置为0 。
输出:
这是我的代码。
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { self.scoutPropertyTable.rowHeight = UITableViewAutomaticDimension + 35 return self.scoutPropertyTable.rowHeight }