UILabelで高さを動的に変えるには
UILabelで高さを動的に変えるには
label.numberOfLines = 0; label.text = @"text"; [label sizeToFit];
とするだけでなんですがsizeToFitが動かない時があります。
sizeToFitのタイミングが悪いと効きません。
ポイントはテキストを設定した後に行う必要があると言うこと。
テキスト設定前にsizeToFitを行なっても意味がありません。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cell == nil) { cell = [self cellWithReuseIdentifier:CellIdentifier]; } UILabel *titleLabel = (UILabel *)[cell viewWithTag:1]; titleLabel.text = @"タイトル"; [titleLabel sizeToFit]; // ここ大事!! titleLabelにテキストを設定した後にsizeToFitをする return cell; } // セルをカスタムする - (UITableViewCell *)cellWithReuseIdentifier:(NSString *)identifier { CGRect frame = CGRectMake(0.0, 0.0, 320.0, 120.0); UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]; //subview UILabel *label; frame = CGRectMake(5.0, 7.0, 200.0, 30.0); label = [[UILabel alloc] initWithFrame:frame]; label.tag = 1; label.numberOfLines = 0; label.font = [UIFont boldSystemFontOfSize:14.0]; [cell.contentView addSubview:label]; return cell; }
このサンプルコードではカスタムのセルを作るのにcellWithReuseIdentifierメソッドにてUILabelの設定を行なっていますがもしこのタイミングで[label sizeToFit]を行なってその後にcellForRowAtIndexPathメソッド にてlabel.text = @"text"だけをやっていると思い通りにいかなくなります。