UITableView インスタンスを持ち、自動レイアウト制約を使用してレンダリングするビューコントローラーがあります。このテーブル ビューでセルの高さを可変にしたいと考えています。セルごとに異なる複数のラベルと画像で構成される複雑なセル コンテンツがあるため、セルの高さを自分で計算したくありません。自動レイアウトセルのサイズを変更して、すべてのサブビューを含めることができると思います(つまり、ラベルにテキストを割り当てた後にラベルの sizeToFit メソッドを使用しますか?)。
自動レイアウトの視覚的制約形式を使用してサブビューを配置するカスタム セル クラスがあります。hereで提案されている方法とそのサンプル実装hereを組み込んでみました。
テーブル ビューを初期化するときに、データ行と同じ長さの配列を作成し、MyCustomCell 型のプロトタイプ セルに値を割り当てて各行の高さを計算し、これを使用してその高さを取得します。
[cell systemLayoutSizeFittingSize:UILayoutFittingExpandedSize].height
それをheights配列に格納して、後でテーブル ビューのheightForRowAtIndexPathメソッドで使用して、個々のセルの正しいセルの高さを取得します。
ただし、これらすべてを実行すると、xCode で読み取り不能な例外NSInternalInconsistencyExceptionが発生し、「受信ヘッド MyCustomCell:0xa8a1430.Width の送信行ヘッドが見つかりません。これは決して発生しないはずです。」
カスタムセルのサブビューの初期化は次のとおりです。
_titleLabel = [[UILabel alloc] init];
_titleLabel.font = [TSTheme boldThemeFontOfSize:TSThemeFontSizeSmall];
_titleLabel.textColor = [[TSTheme sharedTheme] darkTextColor];
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.translatesAutoresizingMaskIntoConstraints = NO;
_titleLabel.font = [UIFont fontWithName:@"HelveticaNeue-CondensedBold" size:19];
_titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.contentView addSubview:_titleLabel];
_summaryLabel = [[UILabel alloc] init];
_summaryLabel.font = [TSTheme boldThemeFontOfSize:TSThemeFontSizeSmall];
_summaryLabel.backgroundColor = [UIColor clearColor];
_summaryLabel.textColor = [[TSTheme sharedTheme] darkTextColor];
_summaryLabel.translatesAutoresizingMaskIntoConstraints = NO;
_summaryLabel.numberOfLines = 0;
_summaryLabel.preferredMaxLayoutWidth = 250.0f; // required for text wrapping
_summaryLabel.font = [UIFont fontWithName:@"Georgia" size:14];
_summaryLabel.lineBreakMode = NSLineBreakByWordWrapping;
[self.contentView addSubview:_summaryLabel];
_thumbnailView = [[UIImageView alloc] init];
_thumbnailView.translatesAutoresizingMaskIntoConstraints = NO;
[self.contentView addSubview:_thumbnailView];
カスタムセルの制約は次のとおりです
NSDictionary *views = NSDictionaryOfVariableBindings(_titleLabel, _summaryLabel, _thumbnailView);
NSDictionary *metrics = @{@"margin": @"5"};
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[_thumbnailView(<=60)]-(margin)-[_titleLabel]-(margin)-|"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_thumbnailView]-(margin)-|"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(margin)-[_titleLabel]-(0)-[_summaryLabel]"
options:0
metrics:metrics
views:views]];
[self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(margin)-[_thumbnailView]-(margin)-[_summaryLabel]-(margin)-|"
options:0
metrics:metrics
views:views]];