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