仿照 QQ 的 cell 的左滑删除、置顶、标记未读效果

侧滑删除、置顶、取消关注,在iOS8之前需要我们自定义,iOS8时苹果公司推出了新的API,UITableViewRowAction类,我们可以使用该类方便的制作出如下图的效果。

下面是实现的主要代码:

// 必须写的方法(否则iOS 8无法删除,iOS 9及其以上不写没问题),和editActionsForRowAtIndexPath配对使用,里面什么不写也行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

// 添加自定义的侧滑功能
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 添加一个删除按钮
    
    UITableViewRowAction *deleteRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        // 先移除数据源数据
        [self.dataArray removeObjectAtIndex:indexPath.row];
        // 再动态刷新UITableView
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
        NSLog(@"删除按钮");
    }];
    
    UITableViewRowAction *topRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"置顶按钮");
        
    }];
    /// 设置按钮颜色,Normal默认是灰色的,Default默认是红色的
    topRowAction.backgroundColor = [UIColor orangeColor];
    
    UITableViewRowAction *cancelRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"取消关注" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"取消关注按钮");
    }];
    
    return @[deleteRowAction,topRowAction,cancelRowAction];
}

只是一个删除按钮,而不显示其他的简单的写法,这个也可以用于IOS7,没有测过。

// 只是一个删除按钮
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

// 删除的处理
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请三思而行再删除" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self.tableView setEditing:NO animated:YES];
    }]];

    [alertController addAction:[UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 先移除数据源数据
        [self.dataArray removeObjectAtIndex:indexPath.row];
        // 再动态刷新UITableView
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
原文地址:https://www.cnblogs.com/benpaobadaniu/p/4866676.html