UITableViewCellの高さを中にあるLabelの大きさで変更する
前の吹出しUIの中にあったのを、必要な部分だけ書き出した。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UILabel *label; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; //ラベルを作成 label = [[UILabel alloc] initWithFrame:CGRectZero]; label.backgroundColor = [UIColor clearColor]; label.tag = 1; label.numberOfLines = 0; label.lineBreakMode = UILineBreakModeWordWrap; label.font = [UIFont systemFontOfSize:14.0]; //土台Viewを作成 UIView *message = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, cell.frame.size.width, cell.frame.size.height)]; message.tag = 0; //それぞれAddする [message addSubview:label]; [cell.contentView addSubview:message]; [message release]; [label release]; }else{ label = (UILabel *)[[cell.contentView viewWithTag:0] viewWithTag:1]; } NSString *text = [messages objectAtIndex:indexPath.row]; //文章のサイズを取得 CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0f, 480.0f) lineBreakMode:UILineBreakModeWordWrap]; //ラベルのサイズを設定 label.frame = CGRectMake(20, 11, size.width + 5, size.height); label.text = text; return cell; } //テーブルセルの高さを設定 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *body = [messages objectAtIndex:indexPath.row]; CGSize size = [body sizeWithFont:[UIFont systemFontOfSize:14.0] constrainedToSize:CGSizeMake(240.0, 480.0) lineBreakMode:UILineBreakModeWordWrap]; return size.height +25; }
ポイントは、ラベルの大きさを取得する「constrainedToSize」みたいだね。
コメントする