tableViewcell上点击删除按钮,对此cell进行删除,弹出UIAlertController提示框确认

需求

tableview上对列表中数据进行删除时弹出窗口进行再次确认
效果如图:
在这里插入图片描述

  • ios 8.0以上的参考,我用的UIAlertController,笔者刚开始学所以UIAlertView没用过

采坑

tableviewrow点击按钮对应的delegate editActionsForRowAtIndexPath实现时, 对应的点击事件UITableViewRowAction *deleteAction的block里面不应该进行删除操作(这样会出现,列表数据删除完毕后才弹框的效果).

解决方法

UIAlertAction *okAction即在UIAlertController的对应按钮事件block中进行数据删除和列表更新操作

代码

//这里是tableview的代理方法
-(NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    //deleteAction
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"del" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath)
    {
        NSLog(@"delete no.%ld item",indexPath.row);
        //这里我把row的行和 indexPath作为参数传进去了 为了删除数据和刷新tableview
        [self askalert: indexPath.row tableindex: indexPath];  //在弹出的alertController里面的block里对tableview就行操作
    }];
 
    return @[deleteAction];
}

//这里是UIAlertController对象创建的方法进行了封装,为了代码看起来简洁
- (void) askalert:(NSInteger)delItemindex tableindex:(nonnull NSIndexPath *)indexPath
{
    //因为用的arc ,为了防止内存泄漏用 __weak, __block是为了在block代码里使用这个tmp变量
    __weak __block XYZToDoListTableViewController *tmp = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Tip" message:@"Are you sure?" preferredStyle:UIAlertControllerStyleAlert];
    
    //取消按钮事件,取消就啥都不做
    __block UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (cancelAction) {
            
        }
    }];
    
    //确认删除的按钮,这里进行数据删除和tableview刷新
    __block UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (okAction) {
		
			//列表数组中删除数据
            [tmp.toDoItems removeObjectAtIndex:delItemindex];   
			
			//刷新tableview
            [tmp.tableView beginUpdates];
            [tmp.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [tmp.tableView endUpdates];
            [tmp savedata:tmp.toDoItems];  //这里是我的业务你们不用看 :> 就是保存数据而已
        }
    }];
    // 添加按钮事件
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    // 显示操作
    [tmp presentViewController:alert animated:YES completion:nil];  
}

之前查了好久没查到,希望能帮到你

猜你喜欢

转载自blog.csdn.net/rhddlr/article/details/87691594