objective-c - 动态计算自定义 UITableViewCell 的高度

我正在构建一个没有 IB 的应用程序,并且我正在从头开始编写所有内容。我有一个自定义的 UITableViewCell,当我尝试计算高度时,它的行为就像没有 subview 一样。我可以找到很多关于动态设置高度的讨论,但没有关于如何根据 subview 以及如何以及在何处设置约束来计算高度的讨论。我所做的是为我的第一个组件 - 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;

}

最佳答案

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

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

您可以在 Using Auto Layout in UITableView for dynamic cell layouts & variable row heights 查看第一个答案

https://stackoverflow.com/questions/31404624/

相关文章:

xslt - 我们如何使用 jenkins 控制台日志通过和失败计数生成 html 报告?

android - RecyclerView 项目有时无法正确显示,直到我滚动(仅在 Genymot

java - 反向路由 玩 POST payload

javascript - limitTo 过滤前查询过滤的 ng-repeat 数据的长度

angularjs - 在剑道下拉列表中选择 "0"作为值的项目

node.js - gulp 段错误 : 11 and Abort trap: 6 OSX Yose

c#-4.0 - 是否有用于验证的设计模式?

java - 动态sql生成设计

javascript - 华丽的弹出式透明 png 为灰色

javascript - 强制 JSON.stringify 使用十进制表示法