2012-07-20 128 views
0

我是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中設置)。如果我增加了尺寸,它會弄亂其他細胞。我需要根據其內容更改標籤的高度。

有人可以幫助我,因爲我花了兩天的試驗和錯誤,仍然沒有設法做到這一點。另外我在這一個小白,所以詳細講解;)

非常感謝

瑞安。

回答

0

我目前正在做同樣的事情。這就是我所做的。

使用sizeToFit方法調整了的UILabel在cellForRowAtIndexPath回調:

[contentViewCell.myTextLabel sizeToFit]; 

希望這會幫助你。