dynamic的UITableCellView高度

我遵循这个教程来启用dynamic细胞高度: http : //www.appcoda.com/self-sizing-cells/

所以我补充说

tableView.estimatedRowHeight = 44.0 tableView.rowHeight = UITableViewAutomaticDimension 

viewDidLoad ,将标签设置为0行和字体设置为系统。 结果是单元格的大小现在是dynamic的,内容显示正确,但不是当表格第一次显示时。 那么一些细胞显示正确,但其他人有44的高度。当我滚动表的高度似乎被纠正。 在教程中,他们描述如下:

当表格视图第一次显示时,您可能会发现一些单元格尺寸不正确。 但是,当您滚动表格视图时,新的单元格将显示正确的行高。 要解决此问题,可以在视图出现后强制重新加载

我试着用

 override func viewDidLoad() { super.viewDidLoad() self.tableView.estimatedRowHeight = 64 self.tableView.rowHeight = UITableViewAutomaticDimension } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.tableView.reloadData() } 

但它不工作。 任何想法如何解决这一问题? 我在Xcode 6.1和iOS8.1上,我正在使用Swift。

我在github上创build了一个简单的testing项目: https : //github.com/ArtworkAD/DynamicCellTest

我下载了你在GitHub上创build的项目,并做了一些修改,并使其工作。

ViewController中的代码看起来像这样…

 import UIKit class MyTableViewController: UITableViewController { var entries:Array<String> = [String]() override func viewDidLoad() { super.viewDidLoad() var i = 0 while i < 20 { entries.append("\(i) Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor") i++; } self.tableView.rowHeight = UITableViewAutomaticDimension } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.entries.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any let cell = self.tableView.dequeueReusableCellWithIdentifier("basic_cell", forIndexPath: indexPath) as UITableViewCell var label = cell.viewWithTag(13) if let unwrappedLabel = label as? UILabel { unwrappedLabel.text = self.entries[indexPath.row] } return cell } } 

故事板看起来像这样…

在这里输入图像说明

请注意从单元格的顶部到底部的AutoLayout约束,并将行数设置为0。

然后当运行应用程序…

在这里输入图像说明

我认为可以在dispatch_once块内的willDisplayCellMethod重新加载表。 这是一个客观的C语法。 你可以快速解决问题

  -(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ [self.tableView reloadData]; }); }