uitableviewcell 内の uilabel のサイズを動的に変更する方法と、ラベルに入力したテキストに応じてテーブル セルの高さを調整する方法に苦労しています。すべてのセルで常に同じフォント サイズで、テーブルビュー セル内に文字列全体を表示したいと考えています。これはかなり標準的なように思えますが、stackoverflow に関する多くの議論/議論/不満に気づきました。私はこれらの投稿から始めました:
JSONファイルのコンテンツテキストに基づいてUILabelを含むカスタムセルのサイズを変更します(@Seyaの回答) NSAttributedStringのboundingRectWithSizeが間違ったサイズを返す(@JOMの回答)
私が使用しようとしている機能は、瀬谷が行ったことをほとんど変更せずにコピーしたものです。ただし、関数はセルごとに異なる高さを出力しますが、多くの行を表示する必要があるにもかかわらず、ラベルごとに 1 行のテキストしか表示されません。また、奇妙なことに、あるセルのテキストが別のセルの上に表示されているようです-これが関連しているかどうかはわかりません.
私の 2 つの質問: (1) テキストの最初の行しか表示されないのはなぜですか? (2) UILabel/cell が、ログに出力されたさまざまな高さに応じてサイズ変更されないのはなぜですか (またはサイズ変更されますが、問題 1 によってマスクされます)。
これが私が使用している3つの関数です(これらはxibと一緒です-xibが問題になる可能性がありますか?):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
JudgeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JudgeCell"];
if(!cell)
{
[tableView registerNib:[UINib nibWithNibName:@"JudgeCell" bundle:nil] forCellReuseIdentifier:@"JudgeCell"];
cell = [tableView dequeueReusableCellWithIdentifier:@"JudgeCell"];
}
cell.username.text = self.object.answerUser[indexPath.row];
cell.answer.text = self.object.answerArray[indexPath.row];
NSString *text = cell.answer.text;
CGSize constraint = CGSizeMake(50, 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];
cell.username.frame = CGRectMake(10, 10, 50, size.height); //MAX(size.height, 14.0f));
return cell;
}
-(CGSize)frameForText:(NSString*)text sizeWithFont:(UIFont*)font constrainedToSize:(CGSize)size {
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
NSDictionary * attributes = @{NSFontAttributeName:font,
NSParagraphStyleAttributeName:paragraphStyle
};
CGRect textRect = [text boundingRectWithSize:size
options:(NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading)
attributes:attributes
context:nil];
NSLog(@"size is %f ", textRect.size.height);
return textRect.size;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
NSString *text = self.object.answerArray[indexPath.row];
CGSize constraint = CGSizeMake(50, 20000.0f);
CGSize size = [self frameForText:text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint];
CGFloat height = size.height; //MAX(size.height, 14.0f);
NSLog(@"size is %f AT INDEX %d", height, indexPath.row);
return height + 20;
}
アドバイスをありがとう!