2011-02-14 60 views
2

我試圖用按鈕刪除單元格。如何用reloadRowsAtIndexPath更新行

這裏是一個單元格的實現。

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; 

     UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
     btn.frame = CGRectMake(0.f, 0.f, 30.f, 30.f); 
     [btn addTarget:self 
       action:@selector(btnTouched:) 
     forControlEvents:UIControlEventTouchUpInside]; 
     [cell addSubview:btn]; 
     cell.tag = indexPath.row; 
    } 
    return cell; 
} 

- (void)btnTouched:(UIButton *)sender 
{ 
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0]; 

    [_myMutableArray removeObjectAtIndex:sender.tag]; 
    [_tableView beginUpdates]; 
    [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] 
         withRowAnimation:UITableViewRowAnimationLeft]; 
    [_tableView endUpdates]; 
} 

這很好的工作,直到我刪除了一行,按鈕沒有重新加載,所以刪除後,我不刪除好索引。我試圖在endUpdates方法後面輸入reloadRowsAtIndexPaths:withRowAnimation:作爲visible indexPath,它工作得很好。但是,reloadRows動畫使刪除動畫變得醜陋(即使我將它設置爲NO)。 所以有沒有reloadCellsAtIndexPath重新加載單元格的方法。或者在不使用標籤的情況下刪除行。


Thx很多。

回答

3

您應該能夠通過使用類似下面的邏輯來查找單元的索引:

NSIndexPath *indexPath = [_tableView indexPathForCell:(UITableViewCell *)[sender superview]]; 

使用這種方法,您不需要將行索引的值存儲在單元標記中。

+0

非常聰明的方式,它的工作。多謝 – klefevre 2011-02-14 17:56:12

0

要剛剛重裝該表(因此它的所有細胞),你可以使用嘗試只:

[_tableView reloadData]; 
+0

我也試過它,它工作得很好。但刪除的動畫並不相同。嘗試有和沒有,你可以看到兩者之間的區別... – klefevre 2011-02-14 17:47:20