2013-10-24 49 views
2

我正在使用自定義單元格爲UITableView,並且上面有一個UIButton,它應該從表格視圖中刪除當前單元格。 在cellForRowAtIndexPath我做無法從UITableView中刪除自定義單元格

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"CellIdentifier"; 
    NSLog(@"Creating Cell"); 

    FADynamicCell *cell= (FADynamicCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 

    if (cell == nil) 
    { 
     cell = [[[NSBundle mainBundle]loadNibNamed:NSStringFromClass([FADynamicCell class]) 
              owner:nil 
              options:nil] lastObject]; 
    } 

    currentIndexPath = indexPath; 

    UIButton *removeButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
    removeButton.tag = indexPath.row +100; 
    removeButton.frame = cell.removeButton.frame; 
    removeButton.backgroundColor = [UIColor colorWithRed:255./255 green:65./255 blue: 21./255 alpha:1]; 
    removeButton.titleLabel.font = [UIFont systemFontOfSize:12]; 
    removeButton.titleLabel.textAlignment = NSTextAlignmentCenter; 
    [removeButton setTitle:@"Remove" forState:UIControlStateNormal]; 
    [removeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; 
    [removeButton addTarget:self action:@selector(removing) forControlEvents:UIControlEventTouchUpInside]; 
    [cell addSubview:removeButton]; 

    return cell; 
} 

而且在功能上正確的細胞去除

-(void) removing 
{ 
    [TOperations deleteTickerFromGroup:tickerGroupID andTickerSymbol:selectedSymbol]; 

    NSNumber *selectedRowIndex1 = [NSNumber numberWithInteger:currentIndexPath.row]; 
    [tableView1 beginUpdates]; 
    NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedRowIndex1.integerValue-1 inSection:0]; 
    [tableView1 endUpdates]; 
    [tableView1 reloadData]; 

} 

現在的問題是,它顯示的動畫,但我不能從表中刪除自定義單元格視圖。每當我再次加載視圖,即來自其他屏幕,它不顯示我點擊刪除的單元格。

任何幫助將不勝感激...

+0

問題可能出在您的數據源中。檢查來自其他屏幕的項目是否仍然存在。 –

+0

@Sviatoslav Yakymiv:當我從其他屏幕來的時候,它不存在,如果我從上面的代碼按下刪除按鈕 – Atul

+0

@Atul,它似乎丟失了你的tableview的數據源。你應該使用一些數組/字典來跟蹤要創建的單元格以及哪些被刪除等。 –

回答

2

要刪除表視圖行/單元格,你需要調用deleteRowsAtIndexPaths:withRowAnimation:方法對你UITableView實例。

NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedRowIndex1.integerValue-1 inSection:0]; 
[self.yourTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade]; 

這將更新用戶界面,但記得要從數據源中刪除該行。這將確保它被完全刪除。

希望有幫助!

+0

:當我使用您的代碼時,它崩潰並顯示:***由於未捕獲異常'NSInternalInconsistencyException',原因:'無效更新:無效的行數在第0節中。終止應用程序中包含的行數在更新(3)之後,必須等於更新前(3)的該部分中包含的行數,加上或減去從該部分插入或刪除的行數(插入0,刪除1)以及加或減移入或移出該部分的行數(移入0,移出0)。' – Atul

+2

發生這種情況是因爲您沒有更新您的數據源,該數據源仍然在方法'numberOfRowsForSection中返回相同數量的行:' – micantox

+0

@Atul您確定indexPath的計算正確嗎?同時確保從數據源中刪除特定的行。 – Amar