动态调整UITableViewCell高度的实现方法
有时我们需要动态调整UITableViewCell的高度,根据内容的不同设置不同的高度,以前看到一种实现方法,写得有点麻烦,具体地址找不到了,这里有个更好的(至少我认为),分享一下部分代码。
2012.03.11更新:一年后回来审视儿时的代码,发现heightForRowAtIndexPath那个实现方法确实不太好,会dequeue掉一个可以reuse的cell导致经常都要新创建cell,会导致效率方面的问题,最好用NSString的sizeWithFont:forWidth:lineBreakMode:这一系列的方法计算label的高度。
- (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;
}
--以上--
5 条历史评论
x
你好....UITableView 的delegate是先执行 -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 然后再执行 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 的............return cell.frame.size.height; 的时候 cell还是生成呢...@__@
G
嗯 这个代码的确是这样,估计作者是为了写起来简洁些 不怕麻烦也可用其他方法 另外我用我那个程序试了一下,多调生成一遍cell对性能也没啥影响
回复
不错,留下记号。。。
H
heightForRowAtIndexPath 方法中调用一下 cellForRowAtIndexPath,这样的话 cellForRowAtIndexPath 就被执行了两次
德哥
恩 好感谢啊 下学习当中 希望早点摆脱菜鸟
评论已关闭。