iOS - 自动调整单元格高度&标签高度

时间:2012-07-20 12:19:50

标签: objective-c ios

我是iOS编程的新手,我正在开发一个具有表格视图的应用程序。

表数据由plist文件加载。桌子的一排很长而且不一致,所以我需要动态的高度。

这是我到目前为止所做的:

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

    NSString *cellText    = @"This is a very long peice of text to show up here and here";// this will eventually be data from a plist
    UIFont *cellFont      = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];
    CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
    CGSize labelSize      = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    int buffer  = 70;
    return labelSize.height + buffer+100;


   //return 65; 

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"CustomTableCell";
    static NSString *CellNib = @"DetailViewCell";



    DetailViewCell *cell = (DetailViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (DetailViewCell *)[nib objectAtIndex:0];


        cell.cellSubtitleLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.cellSubtitleLabel.numberOfLines = 0;
        cell.cellSubtitleLabel.font = [UIFont fontWithName:@"Helvetica-neuve" size:21.0];




    }   

    cell.accessoryType = UITableViewCellAccessoryNone;


    informations = [[NSArray alloc] initWithObjects:@"Title", @"Country", @"State", @"Population",  @"Info",  nil];
    subtitles = [[NSArray alloc] initWithObjects:titleString, subtitleString, stateString, populationString, @"This is a very long peice of text to show up here and here", nil];


    cell.cellTitleLabel.text = [informations objectAtIndex:indexPath.row];
    cell.cellSubtitleLabel.text = [subtitles objectAtIndex:indexPath.row];

    return (DetailViewCell *) cell; 
}

我设法让这个高度合适。但标签文字没有显示。我把它缩小了标签的高度。它在23(在Interface Builder中设置)。如果我增加尺寸,它会弄乱其他细胞。我需要根据标签的内容更改标签的高度。

有人可以帮我解决这个问题,因为我花了两天的时间来试错,但仍然无法做到。我也是一个菜鸟,所以详细解释一下;)

非常感谢

瑞恩。

1 个答案:

答案 0 :(得分:0)

我目前正在做同样的事情。这就是我的工作。

使用cellForRowAtIndexPath方法调整sizeToFit回调中的UILabel大小:

[contentViewCell.myTextLabel sizeToFit];

希望这会对你有所帮助。

相关问题