转载自:http://zhuhaibobb.blog.163.com/blog/static/2744006720127332515450/
其实上边的文章有两种方法好像,但我借鉴的是第二种方法实现,下边是代码:
- (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; //chenyy
注意这个地方设置了cell的frame
}
else {
cellFrame.size.height = 50; //chenyy
注意这个地方设置了cell的frame
}
[cell setFrame:cellFrame];
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
本文介绍了一种在iOS应用中实现自适应高度的UITableViewCell的方法。通过调整单元格的高度来适应其内容,使得文本能够完全显示并且布局更加合理。文中提供了具体的代码实现,包括设置单元格内的UILabel属性和根据文本内容调整cell的高度。
765

被折叠的 条评论
为什么被折叠?



