自定义UITableviewcell高度未正确设置

我在SO上探讨了关于这个问题的现有问答,但没有找到答案。

我知道这是由tableview在运行时不知道自定义单元格的高度引起的,但不知道如何克服这个问题。 这是iOS 8 + Xcode 6.我为自定义单元格的内在大小做了所有自动布局所需的方法…

  • 带有标准单元格的标准tableview,在代码中只创建一个(row = 2)作为自定义单元格;

    customCell:

    -(CGSize)intrinsicContentSize 

    {//硬编码用于测试目的

     return CGSizeMake(500.0, 450.0); 

    }

  • 在iOS模拟器上运行时,发现customCell显示在其行下方的其他单元格下方,高度标准,与设置其他标准​​单元格高度相同,而不是其高度设置比其他单元格大得多。

在表视图控制器中:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; pageViewCellTableViewCell* customCell; if (indexPath.row != 2) { cell = [tableView dequeueReusableCellWithIdentifier:@"regularCell" forIndexPath:indexPath]; cell.textLabel.text = [NSString stringWithFormat:@"Table Row %lu", indexPath.row]; return cell; } else { customCell = [tableView dequeueReusableCellWithIdentifier:@"customCell"] ; if (customCell == nil) { customCell = [[customCell alloc] init]; } customCell.parentViewController = self; [customCell setNeedsUpdateConstraints]; [customCell setNeedsLayout]; [customCell setNeedsDisplay]; return customCell; } return nil ; } - (CGFloat)tableView: (UITableView*)tableView EstimatedHeightForRowAtIndexPath: (NSIndexPath*) indexPath { if (indexPath.row != 2) return 10; else return 450; } - (CGFloat)tableView: (UITableView*)tableView HeightForRowAtIndexPath: (NSIndexPath*) indexPath { if (indexPath.row != 2) return 10; else return 450; } 

在模拟器上运行时:

得到以下错误消息:仅警告一次:检测到约束模糊地建议tableview单元格的内容视图的高度为零的情况。 我们正在考虑无意中崩溃并使用标准高度。

<img src="http://sofzh.miximages.com/ios/KtBO8.png" alt="模拟器的屏幕截图,请参阅第2行被隐藏在其他行这里输入代码“>

您可以在iOS 8(Swift代码)中使用自行resize的单元格:

 tableView.estimatedRowHeight = 88.0 tableView.rowHeight = UITableViewAutomaticDimension 

下面列出了两个教程:

  1. 了解iOS 8中的自定义单元格和动态类型
  2. iOS 8:自动resize表查看具有动态类型的单元格

几天前我遇到了类似的错误。 我建议你再次检查自动布局限制。

设置tableView.rowHeight = UITableViewAutomatic ,必须确保单元格中的每个元素都有前导,上限和下限。 否则swift无法根据内容大小动态更改高度。

弄清楚了。

根据WWDC 2014video“Tableview和Collection View的新function”:

  1. 从self.view添加约束到customTableViewCell.contentView
  2. 将intrinsicSize设置为self.bounds.size

我刚刚处理过这个问题。 我正在从nib文件中执行自定义tableViewCell,而不是使用storyboard单元格。 我按照上面的建议添加了代码(Objective-C):

 self.tableView.rowHeight = UITableViewAutomaticDimension; [self.tableView setEstimatedRowHeight:85.0]; 

没有帮助。 什么帮助修复了我的约束。 我认为通过固定到顶部,然后只设置下两个对象之间的垂直间距就足够了。 我还为UILabels设定了一个固定的高度约束,这会有所帮助。 它没有。 删除任何固定高度约束并将底部对象固定到容器底部解决了我的问题。 事实certificate,自动布局比我聪明。 谁知道!? 大声笑