蘋果已經(jīng)幫我們做好了大部分UI工作, 我們只需要專注數(shù)據(jù)處理即可
設(shè)置navigationbarItem的編輯按鈕, 不用alloc, 直接
self.navigationItem.rightBarButtonItem = self.editButtonItem;
點擊會自動變?yōu)橥瓿? 再點擊會變回編輯, 無需自己寫, 使用self.tableView.editing即可判斷是否進(jìn)入編輯狀態(tài)
然后重寫setEditing方法, 以下用到的兩個數(shù)組一個是保存被選中的indexPath, 一個是保存被選中的cell所擁有的數(shù)據(jù)元素, 每次重新進(jìn)入編輯時初始化
#pragma mark - 重寫setEditing方法
- (void)setEditing:(BOOL)editing animated:(BOOL)animated{
[super setEditing:editing animated:animated];
[_tableView setEditing:!_tableView.editing animated:YES];
if (self.tableView.editing) {
_mArrOfIndex = [NSMutableArray array];
_mArrOfSource = [NSMutableArray array];
[self showDeleteView];
}
else{
[self hideDeleteView];
}
}
以下這句不寫之前, 進(jìn)入編輯后, 全體cell向右縮進(jìn)露出的的是紅色減號, 點擊后是像rowaction一樣向左縮進(jìn)然后露出紅色刪除鍵;
而寫了這句話之后, 全體cell向右縮進(jìn)露出的是灰色圓圈, 點擊可多選, 打上藍(lán)色對勾
_tableView.allowsMultipleSelectionDuringEditing = YES;
以下兩個方法是點擊cell和取消選中的協(xié)議方法,
#pragma mark 點擊row
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView.editing) {
NSString *str = _mArrOfData[indexPath.row];
if (![_mArrOfIndex containsObject:str]) {
[_mArrOfIndex addObject:str];
}
[_mArrOfSource addObject:indexPath];
}
else{
//取消選中狀態(tài)
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
}
#pragma mark 點擊已被點擊過的row
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView.editing) {
//從數(shù)據(jù)數(shù)組取出指定元素
NSString *str = _mArrOfData[indexPath.row];
if ([_mArrOfIndex containsObject:str]) {
[_mArrOfIndex removeObject:str];
}
[_mArrOfSource removeObject:indexPath];
// [_mArrOfIndex removeObject:indexPath];
}
}
我在進(jìn)入編輯時從底部浮上來一個菜單欄, 有刪除和取消兩個button, 對應(yīng)的點擊事件, 先刪數(shù)據(jù), 再更新UI, mArrOfIndex保存的是選中的數(shù)據(jù)們, mArrOfData保存的是選中的indexPath們
kWeakSelf(self);
_bottomDeleteView.deleteArticle = ^(UIButton *btn){
if (_mArrOfIndex.count > 0) {
[weakself.mArrOfData removeObjectsInArray:weakself.mArrOfIndex];
[weakself.tableView deleteRowsAtIndexPaths:weakself.mArrOfSource withRowAnimation:UITableViewRowAnimationLeft];
}
[weakself hideDeleteView];
[weakself.tableView setEditing:NO animated:YES];
weakself.navigationItem.rightBarButtonItem.title = @"編輯";
};
_bottomDeleteView.cancelDelete = ^(UIButton *btn){
[weakself hideDeleteView];
[weakself.tableView setEditing:NO animated:YES];
weakself.navigationItem.rightBarButtonItem.title = @"編輯";
};
以下這倆方法應(yīng)該是在單選時才生效
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
}