2011-12-23 48 views
0

我試圖讓單元在已經展開的情況下摺疊。此代碼在點擊時正在擴展該行,但在heightForRowAtIndexPathbool cell.cell_expanded始終爲FALSE。我試過[tableView reloadData]但這並沒有辦法。任何想法?如何將來自didSelectRowAtIndexPath的CustomCell數據中的更改傳遞給heightForRowAtIndexPath

我讀過使用heightForRowAtIndexPath可以對性能產生巨大影響,所以如果可能的話我想刪除這個方法調用。是否有可能在其他地方重構此功能?

下面是我有:

CustomCell.h

@interface CustomCell : UITableViewCell 
{ 
    UIImageView *cell_arrow; 
    BOOL cell_expanded; 
} 
@property (nonatomic, strong) UIImageView *cell_arrow; 
@property (nonatomic) BOOL cell_expanded; 

FirstViewController.m

-(void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    selectedCellIndexPath = indexPath; 

    CustomCell *cell = (CustomCell *)[tv cellForRowAtIndexPath:indexPath]; 

    NSString *arrow = nil; 
    if (cell.cell_expanded == TRUE) { 
     arrow = @"arrow_down.png"; 
     cell.cell_expanded = FALSE; 
    } 
    else { 
     arrow = @"arrow_up.png"; 
     cell.cell_expanded = TRUE; 
    } 
    cell.cell_arrow.image = [UIImage imageNamed:arrow]; 

    [self.tableView beginUpdates]; 
    [self.tableView endUpdates]; 
} 

-(CGFloat)tableView:(UITableView *)tv heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    CustomCell *cell = (CustomCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath]; 
    if (selectedCellIndexPath != nil) { 
     if (indexPath.row == selectedCellIndexPath.row) { 
      NSLog(@"cell_expanded = %d for row %i", cell.cell_expanded, indexPath.row); 
      CGSize theSize = [cell.cell_body.text sizeWithFont:[UIFont systemFontOfSize:12.0f] constrainedToSize:CGSizeMake(265.0f, 9999.0f) lineBreakMode:UILineBreakModeWordWrap]; 
      if (cell.cell_expanded == TRUE) { 
       NSLog(@"open it"); 
       return theSize.height + 16; 
      } else { 
       NSLog(@"close it"); 
       return 44; 
      } 
     } 
     else { 
      return 44; 
     } 
    } 
    return 44; 
} 

回答

-1

好吧,兩件事情在這裏:

1)只需調用-reloadData而不是-end/beginUpdates。 2)你顯然不明白UITableView的工作原理。 UITableView重用它的單元格。這意味着你可能有5個單元格實例。你應該閱讀關於它的documents。爲了解決你的問題,你應該將擴展變量保存在由UITableView表示的實例變量中。

相關問題