Iphone UITableViewCell-具有文本自适应视图高度的布局子视图

Iphone UITableViewCell-具有文本自适应视图高度的布局子视图,iphone,objective-c,uitableview,Iphone,Objective C,Uitableview,当我创建自己的UITableViewCell时,我使用layoutSubviews来排列单元格中的元素。 但是,如何创建一个适合所需行数的区域-取决于描述文本的长度 -(void) layoutSubviews { [super layoutSubviews]; [imageView setFrame:CGRectMake(8.0, 10.0, 20.0, 20.0)]; [description setFrame:CGRectMake(40.0, 1.0, 250.0

当我创建自己的
UITableViewCell
时,我使用
layoutSubviews
来排列单元格中的元素。 但是,如何创建一个适合所需行数的区域-取决于描述文本的长度

-(void) layoutSubviews {
    [super layoutSubviews];

    [imageView setFrame:CGRectMake(8.0, 10.0, 20.0, 20.0)];
    [description setFrame:CGRectMake(40.0, 1.0, 250.0, 40.0)]; //1..n lines  <- ???????

}

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {

        imageView = [[UIImageView alloc] initWithFrame: CGRectZero];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.contentView addSubview: imageView];

        titleLabel = [[UILabel alloc] initWithFrame: CGRectZero];
        [titleLabel setFont:[UIFont systemFontOfSize:14.0]];
        [titleLabel setTextColor:[UIColor blackColor]];
        [titleLabel setHighlightedTextColor:[UIColor darkGrayColor]];
        [titleLabel setLineBreakMode: NSLineBreakByWordWrapping];
        //titleLabel.numberOfLines = 2;
        [self.contentView addSubview: titleLabel];

        description = [[UILabel alloc] initWithFrame: CGRectZero];
        [description setFont:[UIFont systemFontOfSize:12.0]];
        [description setTextColor:[UIColor darkGrayColor]];
        [description setHighlightedTextColor:[UIColor darkGrayColor]];
        [description setLineBreakMode: NSLineBreakByWordWrapping];
        //description.numberOfLines = 1;                     //1..n lines  <- ???????
        [self.contentView addSubview: description];
}
-(无效)布局子视图{
[超级布局子视图];
[imageView设置帧:CGRectMake(8.0,10.0,20.0,20.0)];

[description setFrame:CGRectMake(40.0,1.0,250.0,40.0)];/1..n行您必须通过计算要放置在单元格中的字符串(单元格内容)的大小来获得单元格的高度。此计算应为:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

计算出高度后,您必须相应地调整/放置单元格内元素(单元格内容)的框架。

表格单元格不确定其自身的高度。相反,UITableView会布置单元格。现在,
UITableView
有一个委托方法:
-(CGFloat)tableView:(UITableView*)tableView HeightForRowatineXpath:(NSIndexPath*)indexPath
。但是,在表显示其数据之前,它将为表中的每一行调用该方法(或调用
CellForRowatineXpath
委托方法)。这是因为
UITableView
需要知道其大小(或高度)表格将在开始显示数据之前显示,因为它使用此信息设置内容大小、确定滚动条高度等。这意味着,如果希望表格单元格具有可变单元格高度,则需要在加载表格之前计算这些单元格高度。如果表格很小,则这没有问题,但是如果您的表很大或计算复杂,则可能会在显示表时产生延迟。因此,您通常希望“RowatinePath
高度”非常有效

但一旦完成此操作(计算行高),除了布局子视图外,您不需要在
UITableViewCell
子类中执行任何操作。单元格高度将已经为您设置