----- TableView 刪除和添加 -----
** UITableView 編輯步驟
1.讓 tableView 處于編輯狀態(tài)
2.協(xié)議確定
1)確定 cell 是否處于編輯狀態(tài)
2)設定 cell 的編輯樣式(刪除、添加)
3) 編輯狀態(tài)進行提交**
-
開啟編輯狀態(tài)
//1.讓 tableView 處于編輯狀態(tài) [tableView setEditing:YES animated:YES];
如果沒有開啟編輯狀態(tài)放钦,沒有左邊的小紅點
Paste_Image.png
- 1)確定 cell 是否處于編輯狀態(tài)
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- 2)設定 cell 的編輯樣式(刪除色徘、添加)
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//插入
// return UITableViewCellEditingStyleInsert;
//刪除
return UITableViewCellEditingStyleDelete;
}
- 3) 編輯狀態(tài)進行提交
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (editingStyle) {
case UITableViewCellEditingStyleNone:
{
}
break;
case UITableViewCellEditingStyleDelete:
{
//修改數(shù)據(jù)源,在刷新 tableView
[_dataSource removeObjectAtIndex:indexPath.row];
//讓表視圖刪除對應的行
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
break;
case UITableViewCellEditingStyleInsert:
{
[_dataSource insertObject:@"我是新增" atIndex:indexPath.row];
//讓表視圖添加對應的行
[tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
break;
default:
break;
}
}
- 修改 Delete 文字
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
return @"刪除";
}
刪除.gif
添加.gif
----- TableView 移動 -----
- 1.實現(xiàn)協(xié)議:告訴 tableView 是否能夠移動
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- 2.移動
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
//修改數(shù)據(jù)源
[_dataSource exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];
//讓表視圖對應的行進行移動
[tableView exchangeSubviewAtIndex:sourceIndexPath.row withSubviewAtIndex:destinationIndexPath.row];
}
移動.gif