2

我正在构建一个没有 IB 的应用程序,并且我正在从头开始编写所有内容。我有一个自定义 UITableViewCell ,当我尝试计算高度时,它的行为就像没有子视图一样。我可以找到很多关于动态设置高度的讨论,但没有真正关于如何计算它,基于子视图以及如何以及在哪里设置约束。我所做的是为我的第一个组件 - UIImageView 设置约束并将它们添加到我的单元格的 contenView 中。我得到的是0。

我将不胜感激有关该或至少方向的任何意见!

heightForRowAtIndexPath:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell* cell = [[UITableViewCell alloc]init];
    cell.imageView.image = [UIImage imageNamed:@"avatar"];

    cell.imageView.translatesAutoresizingMaskIntoConstraints=NO;

    NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-30-[image]" options:0 metrics:nil views:@{ @"image": cell.imageView }];

    [cell.contentView addConstraints:constraints];

    NSArray *constraints2 = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-20-[image]" options:0 metrics:nil views:@{ @"image": cell.imageView}];

    [cell.contentView addConstraints:constraints2];

    [ NSLayoutConstraint constraintWithItem:cell.imageView attribute: NSLayoutAttributeWidth
                                  relatedBy:NSLayoutRelationEqual toItem:cell.imageView attribute:NSLayoutAttributeHeight multiplier:1.0 constant:0.0f];

     CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;

    NSLog(@"%f",height);

    return height;

}
4

2 回答 2

0

我对这类问题的解决方案是UITableViewAutomaticDimension. 您只需在heightForRowAtIndexPath方法中返回它。您必须设置tableView.estimatedRowHeight一些接近您将获得的值。

例如,如果您有 5 个高度为 [100,200,250,270,300] 的单元格,您可以设置estimatedRowHeight为 220(或类似的值)。

您可以查看在UITableView 中使用自动布局进行动态单元格布局和可变行高的第一个答案。

于 2015-07-14T11:06:08.533 回答
0

我不确定这会起作用,或者它是否正确,但请尝试这种方式

static NSInteger someCell = 1;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [UITableViewCell new];
    cell.tag = someCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell.tag == someCell) return 100.;
    return 30.;
}
于 2015-07-14T11:08:43.943 回答