动态调整UITableViewCell高度的实现方法

本文介绍了一种在UITableView中动态调整单元格高度的方法。通过在cellForRowAtIndexPath方法中计算UILabel的高度,并据此设置UITableViewCell的高度,实现了自适应内容长度的布局效果。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
 
    static NSString *CellIdentifier = @"Cell";
 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
		label.tag = 1;
		label.lineBreakMode = UILineBreakModeWordWrap;
		label.highlightedTextColor = [UIColor whiteColor];
		label.numberOfLines = 0;
		label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制
		label.backgroundColor = [UIColor clearColor];
		[cell.contentView addSubview:label];
		[label release];
    }
 
    UILabel *label = (UILabel *)[cell viewWithTag:1];
	NSString *text;
	text = [textArray objectAtIndex:indexPath.row];
    CGRect cellFrame = [cell frame];
	cellFrame.origin = CGPointMake(0, 0);
 
	label.text = text;
	CGRect rect = CGRectInset(cellFrame, 2, 2);
	label.frame = rect;
	[label sizeToFit];
	if (label.frame.size.height > 46) {
		cellFrame.size.height = 50 + label.frame.size.height - 46;
	}
	else {
		cellFrame.size.height = 50;
	}
	[cell setFrame:cellFrame];
 
    return cell;
}
 
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        //UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];
	return cell.frame.size.height;
}

本文转载至 http://longtimenoc.com/archives/动态调整uitableviewcell高度的实现方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值