自定义UITableviewcell高度未正确设置

3

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

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

  • Standard tableview with standard cells, only one (row = 2) created in code as custom cell;

    customCell:

    -(CGSize)intrinsicContentSize
    

    { //hardcode for testing purposes

    return CGSizeMake(500.0, 450.0);
    

    }

  • when running on iOS simulator, found that the customCell is displayed "underneath" other cells below its row, with height standard, the same way other standard cell height is set, instead of its height set much bigger than other cells.

在表格视图控制器中:

- (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;
 }

当在模拟器上运行时:

收到以下错误消息: 仅警告一次: 检测到约束模棱两可,建议将表格视图单元格的内容视图高度设置为零。我们认为这是意外的折叠,因此使用标准高度。

模拟器截图,第二行被挤压在其他行下面<code>输入代码</code>

5个回答

6

几天前我遇到了类似的错误。建议您再次检查自动布局约束。

在设置tableView.rowHeight = UITableViewAutomatic时,您必须确保单元格中的每个元素都有先导、顶部和底部约束。否则,Swift将无法根据内容大小动态更改高度。


3
这很有帮助 - 调整约束的优先级(并使用<=)也可以避免一旦所有约束都被添加就会出现冲突约束的不同错误。 - Speedy99

4

2

我也遇到了这个问题。我正在使用一个来自nib文件的自定义tableViewCell,而不是使用storyboard cell。我添加了如上所述的代码(Objective-C):

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

没有帮助。真正有用的是修复我的约束条件。我以为只需将对象固定在顶部,然后设置下两个对象之间的垂直间距就足够了。我还设置了UILabel的固定高度约束,以为这会有所帮助。但事实证明并不是这样的。删除任何固定高度的约束,并将底部对象固定在容器的底部,解决了我的问题。原来自动布局比我聪明。谁知道呢!哈哈


2

我搞定了。

根据WWDC 2014视频中“Tableview和Collection View的新内容”:

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

0

我曾经遇到过使用两个标签时UITableViewCell垂直压缩的问题。

像Mike C.提到的那样将底部间距设置为容器也对我有帮助。

右键单击并从标签边界框的左侧拖动(外部标签边界框,而不是标签名称本身)到内容视图的左下方即可打开约束视图。选择“底部空间到容器”-完成。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接