- (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
以上源代碼可在模擬器模式下正常運行,已測試。