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得られる値に近い値に設定する必要があります。

たとえば、高さが [100,200,250,270,300] のセルが 5 つある場合、estimatedRowHeight220 (または同様のもの) に設定できます。

Using Auto Layout in UITableView for dynamic cell layouts & variable row heightsの最初の回答もご覧ください。

于 2015-07-14T11:06:08.533 に答える