以下程式碼的作用是:當你點擊選中 tableview 的某一行時,它會記錄被選中的行;當你左掃並刪除某一行時,它會刪除該行資料並更新 tableview 中的資料。
@interface DummyTableViewController : UITableViewController
@property (nonatomic, strong) NSMutableArray *items;
@end
@implementation DummyTableViewController
- (instancetype)initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) {
_items = [@[@"A", @"B", @"C", @"D", @"E"] mutableCopy];
}
return self;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:nil];
cell.textLabel.text = self.items[indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.items removeObjectAtIndex:indexPath.row];
[tableView reloadData];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(@"Row %@ tapped.", self.items[indexPath.row]);
}
在 iOS 6 環境下,上述程式碼如預期般運作。但在 iOS 7 環境下,當 tableview 中的一行被刪除並更新後,被刪除行的下一行的點擊事件將被忽略,導致點擊該行無反應。原因如下。
當 tableview 中的某行被選中刪除後,tableview 會處於編輯(editing)狀態,所以你需要把 tableview 的狀態換回選擇(selection)模式,更改程式碼如下:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.items removeObjectAtIndex:indexPath.row];
tableView.editing = NO; // 在這裡關閉編輯狀態
[tableView reloadData];
}
}
註:本人水平有限,翻譯錯誤在所難免,如有錯誤望指正。
原文:https://stackoverflow.com/questions/19364409/uitableviewcontroller-ignores-tap-after-deleting-row-in-ios7