2013-07-31 25 views
2

我希望實現的tableview其中顯示了特定行的可擴展電池,所以我創建這將如果設置它的expandContent如下擴大我自定義表格單元格:如何指定行的高度?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"Cell"; 
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    NSString *shouldExpand = [self.datasource objectAtIndex:indexPath.row]; 
    if([shouldExpand isEqualToString:@"expand"]){ 
     [cell setExpandContent:@"Expand"]; 
    } 
    else{ 
     [cell setTitle:@"a line"]; 
    } 
    return cell; 
} 

然而,爲了告訴tableview中行高度,我需要執行下面的代碼:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 
    return [cell cellHeight]; 
} 

的問題是heightForRowAtIndexPath方法調用的tableView的1000次:的cellForRowAtIndexPath:如果我的數據源中包含1000個數據,它花費太多的時間。

如何解決這一問題?

+0

不要叫的cellForRowAtIndexPath那麼,它的怪異做到這一點呢。請改爲查詢您的數據源。 – borrrden

+0

你的細胞只有兩種尺寸?所有未展開的單元格的高度是否相同,並且所有展開的行都是相同的高度? –

+0

所有非增殖的細胞都是相同的高度,但不是所有的擴展行是@rob mayoff – NOrder

回答

2

不應該先找到單元格的大小然後發送hight計算出來,不要調用tableView:cellForRowAtIndexPath:它會導致遞歸,而是首先計算併發送高度。例如

  //say suppose you are placing the string inside tableview cell then u need to calculate cell for example 

    NSString *string = @"hello world happy coding"; 
    CGSize maxSize = CGSizeMake(280, MAXFLOAT);//set max height 
    CGSize cellSize = [self.str sizeWithFont:[UIFont systemFontOfSize:17] 
        constrainedToSize:maxSize 
        lineBreakMode:NSLineBreakByWordWrapping];//this will return correct height for text 
    return cellSize.height +10; //finally u return your height 


0

這是我用於設置動態地的UITableViewCell高度的代碼:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 
    NSDictionary* dict = [branchesArray objectAtIndex:indexPath.row]; 
    NSString* address = [NSString stringWithFormat:@"%@,%@\n%@\n%@\n%@",[dict objectForKey:@"locality"],[dict objectForKey:@"city"],[dict objectForKey:@"address"],[dict objectForKey:@"contactNumber"], [dict objectForKey:@"contactEmail"]]; 

    CGSize constraint = CGSizeMake(220, MAXFLOAT); 

    CGSize size = [address sizeWithFont:[UIFont fontWithName:@"Helvetica" size:14.0f] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping]; 

    CGFloat height1 = MAX(size.height, 110.0f); 
    return height1+20; 
} 

以及設置幀在 - (的UITableViewCell *)的tableView: (UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath也

1

如何解決這個問題?

如果你真的有1000行,你應該使用動態行高,因爲即使你想出了一個快速的方法來確定該行高度表將仍然需要問的高度考慮分開。 (事實上​​,如果你真的有1000行,你應該重新考慮你的整個設計 - 這是太多的數據不能通過線性接口查看。)

如果您必須使用大量行的動態行高,您至少需要找到一種快速確定高度的方法,而無需創建整個單元格。也許你可以確定影響行高的因素,並提出一個非常簡單的方法來計算高度。如果你不能這樣做,那麼計算每一行的高度就可能是有意義的,然後用行數據保存結果,以便在數據改變之前不必再計算結果。