[转]让UITableView中的单元格根据内容的多少自动调整高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; { NSString *text = [items objectAtIndex:[indexPath row]];
//下句中(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2) 表示显示内容的label的长度 ,20000.0f 表示允许label的最大高度
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; CGFloat height = MAX(size.height, 44.0f); return height + (CELL_CONTENT_MARGIN * 2); } - (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell; UILabel *label = nil; cell = [tv dequeueReusableCellWithIdentifier:@"Cell"]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"] autorelease]; label = [[UILabel alloc] initWithFrame:CGRectZero]; [label setLineBreakMode:UILineBreakModeWordWrap]; [label setMinimumFontSize:FONT_SIZE]; [label setNumberOfLines:0]; [label setFont:[UIFont systemFontOfSize:FONT_SIZE]]; [label setTag:1]; [[label layer] setBorderWidth:2.0f]; [[cell contentView] addSubview:label]; } NSString *text = [items objectAtIndex:[indexPath row]]; CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap]; if (!label) label = (UILabel*)[cell viewWithTag:1]; [label setText:text]; [label setFrame:CGRectMake(CELL_CONTENT_MARGIN, CELL_CONTENT_MARGIN, CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), MAX(size.height, 44.0f))]; return cell; }
源代码下载:http://download.csdn.net/detail/ygm900/5404317
以上源代码可在模拟器模式下正常运行,已测试。