點擊編輯按鈕,使UITableView處于編輯狀態(tài),UITableViewCell可以選中取消,選中時自定義選中圖片.之后點擊刪除按鈕,刪除選中狀態(tài)下的Cell.如圖:
解釋下主要的代碼:
1.UITableView 是否可以進(jìn)入編輯狀態(tài),可根據(jù)indexPath設(shè)置需要編輯的section和row.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
2.@property (nonatomic, getter=isEditing) BOOL editing; 打開關(guān)閉編輯模式.
- (void)editingCilck:(UIButton *)sender{
sender.selected = !sender.selected;
if (sender.selected) {
[sender setTitle:@"完成" forState:UIControlStateNormal];
[self.view addSubview:self.editView];
//啟動表格的編輯模式
self.deleteTableView.editing = YES;
}else{
[sender setTitle:@"編輯" forState:UIControlStateNormal];
[self.editView removeFromSuperview];
//關(guān)閉表格的編輯模式
self.deleteTableView.editing = NO;
}
}
3.設(shè)置編輯樣式(如果不設(shè)置,會使用系統(tǒng)自帶的刪除方法,不能多選刪除,只能單個刪除. 會調(diào)用注釋掉的那個方法)
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}
// 系統(tǒng)自帶的單個刪除的方法
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
//
// if (editingStyle == UITableViewCellEditingStyleDelete) {
// [self.dataArray removeObjectAtIndex:indexPath.row];
// [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
// }
//}
4.取出系統(tǒng)自帶的選中視圖
UIImageView *imageView = [[[cell.subviews lastObject]subviews]firstObject];
解釋: 在TableView允許編輯狀態(tài)下點擊Cell, 打印 cell.subviews,其中UITableViewCellEditControl 即為編輯狀態(tài)下的視圖, [[cell.subviews lastObject]subviews] 選中狀態(tài)下的視圖.
5.解決Cell在復(fù)用時,自定義的選中按鈕不會被系統(tǒng)還原.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
// 此處要使用帶 forIndexPath: 的這個方法.否則自定義選中視圖,在Cell的復(fù)用中會變回系統(tǒng)自帶的按鈕圖片.
DeleteViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DeleteViewCell" forIndexPath:indexPath];
cell.deleteLable.text = self.dataArray[indexPath.row];
//此處一定不能使用 UITableViewCellSelectionStyleNone, 會造成選中之后再次點擊無法改變選中視圖的樣式(會有很多問題,可以試試哈)
cell.selectionStyle = UITableViewCellSelectionStyleDefault;
//復(fù)用過程中,自定義的選中按鈕不會被系統(tǒng)還原,需配合上述 forIndexPath: 方法(需在 Cell選中狀態(tài) 和 TableView編輯狀態(tài)下)
if (cell.selected == YES && tableView.editing == YES) {
UIImageView *imageView = [[[cell.subviews lastObject]subviews]firstObject];
imageView.image = [UIImage imageNamed:@"chose_06"];
}
return cell;
}
6.用于監(jiān)聽刪除數(shù)據(jù)中數(shù)組的個數(shù)
[RACObserve(self, number) subscribeNext:^(id x) {
}];
代碼在這里-- Demo
END.