2010-09-20 57 views
1

我只知道第一步是檢查一行。 接下來,我覺得是用NSMutableArray記錄哪一行被選中, ,這是我的代碼:iphone SDK:如何使用複選標記刪除行被檢查?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
     if ([[tableView cellForRowAtIndexPath:indexPath] accessoryType] == UITableViewCellAccessoryCheckmark){ 

       [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryNone]; 
      } 

      else { 

       [[tableView cellForRowAtIndexPath:indexPath] setAccessoryType:UITableViewCellAccessoryCheckmark]; 

     } 
    } 

所以,我的問題是:

  1. 如何把這個檢查行的indexPath成陣列?

  2. 如何添加一個刪除按鈕,我可以刪除我選擇的所有行?

回答

2

首先在viewController的.h文件中聲明一個NSMutableArray。

像這樣:

NSMutableArray *checkedRows; 

變化的youre didSelectRow方法是這樣的:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if ([checkedRows containsObject:indexPath]) { 
     [checkedRows removeObject:indexPath]; 
    } 
    else { 
     [checkedRows addObject:indexpath]; 
    } 
    [self.tableView beginUpdates]; //Just for animation.. 
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    [self.tableView endUpdates]; 
} 

而且在您選擇cellForRow方法補充一點:

if ([checkedRows containsObject:indexPath]){ 
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
} 
else { 
    cell.accessoryType = UITableViewCellAccessoryNone; 
} 
+0

謝謝我現在就試試這個方法! – 2010-09-20 12:52:11

+0

soory,我登錄checkedRows時得到空... ...? – 2010-09-20 13:01:42

+0

對不起,我沒有注意到問題的第二部分..這將只處理檢查行.. checkedRows爲null的原因很可能是因爲你沒有在viewDidLoad中分配它。像:checkedRows = [[NSMutableArray alloc] init ]。 也在dealloc中釋放它[checkedRows release]; 做一些像TechZen recomended .. – LarsJK 2010-09-20 13:07:07

1

你要對這個錯誤的。

您不會自己處理編輯附件視圖。相反,您將setEditing:animated:發送到表格,併爲您更改單元格。那麼你需要實現:

– tableView:commitEditingStyle:forRowAtIndexPath: 
– tableView:canEditRowAtIndexPath: 

...實際上刪除行單元格。