iOS开发系列 ---- UI (TableView的编辑和多项删除操作)

增加、删除和移动效果图:
编辑和移动

实现核心代码:

#import "ViewController.h"

@interface ViewController ()<
UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *arrayDS;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isEditing;//当前状态可否编辑

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupDatas];
    [self setupSubviews];
}

- (void)setupDatas {
    self.isEditing = NO;
    self.arrayDS = [[NSMutableArray alloc] init];
    NSMutableArray * arrayBoys = [[NSMutableArray alloc] init];
    NSMutableArray * arrayGirls = [[NSMutableArray alloc] init];
    for (int i = 0; i < 20; i++) {
        NSString * str1 = [NSString stringWithFormat:@"男同学%d号",i+1];
        NSString * str2 = [NSString stringWithFormat:@"女同学%d号",i+1];
        [arrayBoys addObject:str1];
        [arrayGirls addObject:str2];
    }
    [self.arrayDS addObject:arrayBoys];
    [self.arrayDS addObject:arrayGirls];
}

- (void)setupSubviews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"表格视图";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];

    //在导航条上添加编辑按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.arrayDS count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[_arrayDS objectAtIndex:section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ///<1.>设置标识符
    static NSString * str = @"cellID";
    ///<2.>根据这个标识符 去队列里面找一找用木有空余的
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    ///<3.>如果cell不存在,则新建cell
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    ///<4.>设置信息、刷新数据
    cell.textLabel.text = _arrayDS[indexPath.section][indexPath.row];

    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"男同学";
    } else {
        return @"女同学";
    }
}

/**
 *  点击编辑按钮,开启当前表格的编辑状态
 */
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    //1、调用父类中的setEditing方法
    [super setEditing:editing animated:animated];
    //2、将标识表格编辑状态的变量变为相反值
    _isEditing = !_isEditing;
    //3、开启/关闭表格的编辑状态
    [_tableView setEditing:_isEditing animated:YES];
}

/**
 *  设置单元格的编辑样式(默认情况下单元格的编辑样式为删除样式)
 */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return UITableViewCellEditingStyleDelete;
    } else {
        return UITableViewCellEditingStyleInsert;
    }
}

/**
 *  实现删除、添加单元格操作
 *  删除操作,先删除数组中的元素,再删除相应索引处的单元格
 *  添加操作,先在数组中插入元素,再在相应索引处插入新的单元格
 */
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //获取删除的元素(单元格)处于哪个分区
        NSMutableArray * arrDelete = [_arrayDS objectAtIndex:indexPath.section];
        //根据分区的区号来删除对应数组中的元素
        [arrDelete removeObjectAtIndex:indexPath.row];
        /**
         *  从表格上删除单元格
         *  第一个参数:添加的是删除单元格所在区域的数组
         *  第二个参数:添加的删除单元格带有的动画效果
         */
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationRight];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        //获取添加的元素(单元格)处于哪个分区
        NSMutableArray * arrayInsert = [_arrayDS objectAtIndex:indexPath.section];
        //向数组添加元素
        [arrayInsert insertObject:@"new" atIndex:indexPath.row];
        /**
         *  在表格的相应索引处添加单元格
         *  第一个参数:添加的是删除单元格所在区域的数组
         *  第二个参数:添加的删除单元格带有的动画效果
         */
        [tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

/**
 *  设置单元格移动样式
 */
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

/**
 *  第二个参数:表示将要移动的单元格所处的位置
 *  第三个参数:表示移动到哪个位置
 */
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    //获取需要删除的元素数组
    NSMutableArray * arrayDelete = [_arrayDS objectAtIndex:sourceIndexPath.section];
    //保存删除的元素内容
    NSString * str = [arrayDelete objectAtIndex:sourceIndexPath.row];
    //从数组中删除该元素
    [arrayDelete removeObjectAtIndex:sourceIndexPath.row];
    //获取添加元素所在的数组
    NSMutableArray * arrayInsert = [_arrayDS objectAtIndex:destinationIndexPath.section];
    [arrayInsert insertObject:str atIndex:destinationIndexPath.row];
}

@end

编辑demo

多项删除效果图:
多项删除效果图

实现核心代码:

#import "ViewController.h"

@interface ViewController ()<
UITableViewDataSource,
UITableViewDelegate>

@property (nonatomic, strong) NSMutableArray *arrayDS;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) BOOL isEditing;//用来标识此时表格视图的状态
@property (nonatomic, strong) NSMutableArray *arrayRemove;//存放删除的所有元素

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupDatas];
    [self setupSubviews];
}

- (void)setupDatas {
    self.isEditing = NO;
    self.arrayRemove = [[NSMutableArray alloc] init];
    self.arrayDS = [[NSMutableArray alloc] init];
    for (int i = 0; i < 10; i++) {
        NSString * str = [NSString stringWithFormat:@"同学%d",i+1];
        [self.arrayDS addObject:str];
    }
}

- (void)setupSubviews {
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"表格视图";
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];

    //在导航条上添加编辑按钮
    self.navigationItem.rightBarButtonItem = self.editButtonItem;

    //将按钮添加到表格的底部
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 300, 44);//有效值只有宽高
    [button setTitle:@"删除" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.backgroundColor = [UIColor redColor];
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableFooterView = button;
}

- (void)buttonClick:(UIButton *)button {
    if (self.isEditing) {
        //先移除数据源中与删除数组中相同的元素信息
        [self.arrayDS removeObjectsInArray:_arrayRemove];
        //清空删除数组中的内容,如果不清空删除数组中的内容,下一次删除操作就会在删除数组的内容基础上继续追加,那么第一步的移除操作一定会崩溃
        [self.arrayRemove removeAllObjects];
        //刷新表格
        [self.tableView reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _arrayDS.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString * str = @"cellID";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str];
    }
    cell.textLabel.text = _arrayDS[indexPath.row];
    return cell;
}

/**
 *  开启/关闭表格编辑状态
 */
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    self.isEditing = !self.isEditing;
    if (self.isEditing == NO) {
        [self.arrayRemove removeAllObjects];
    }
    [self.tableView setEditing:self.isEditing animated:YES];
}

/**
 *  设置单元格的编辑样式:
 */
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

/**
 *  触发cell点击事件
 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //通过判断表格是否处于编辑状态 来决定单元格的状态
    if (self.isEditing) {
        [self.arrayRemove addObject:[self.arrayDS objectAtIndex:indexPath.row]];
    }
}

/**
 *  选中的单元格再次点击就处于非选中状态
 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    //获取非选中单元格中的内容
    NSString * str = [_arrayDS objectAtIndex:indexPath.row];
    //判断删除数组是否存在非选中单元格的内容
    if ([self.arrayRemove containsObject:str]) {
        [self.arrayRemove removeObject:str];
    }
}

@end

多项删除操作demo

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 开发中,TableView 是一个非常重要的视图控件,用于展示大量数据。而 TableView 中的 HeaderView 和 FooterView 也是非常重要的组件,可以用于展示一些额外的信息或者操作按钮。在 TableView 中,我们可以通过注册重用标识符来复用 Cell,但是对于 HeaderView 和 FooterView 却没有提供类似的注册方法。本文将介绍如何在 TableView 中循环利用 HeaderView,并且还会介绍如何自定义 HeaderView。 ## 循环利用 TableView 中的 HeaderView 在 TableView 中,我们可以通过以下方法来设置 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)]; headerView.backgroundColor = [UIColor grayColor]; return headerView; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; } ``` 上面的代码中,我们通过实现 `tableView:viewForHeaderInSection:` 方法来设置 HeaderView 的内容和样式,通过实现 `tableView:heightForHeaderInSection:` 方法来设置 HeaderView 的高度。但是如果我们在 TableView 中有很多组数据,每次都创建一个新的 HeaderView 会非常消耗性能,因此我们需要对 HeaderView 进行循环利用。 循环利用 HeaderView 的实现方法非常简单,我们只需要在 TableView 的代理方法中通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法来获取 HeaderView,如果获取到的 HeaderView 为 nil,就创建一个新的 HeaderView,否则就返回重用的 HeaderView。 ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; if (!headerView) { headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerIdentifier]; headerView.contentView.backgroundColor = [UIColor grayColor]; } return headerView; } ``` 上面的代码中,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取重用的 HeaderView。如果获取到的 HeaderView 为 nil,我们就创建一个新的 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。最后,我们设置 HeaderView 的背景颜色,并且返回 HeaderView。 ## 自定义 TableView 中的 HeaderView 除了循环利用 HeaderView,我们还可以自定义 HeaderView。自定义 HeaderView 的方法与自定义 Cell 的方法类似,我们需要在 XIB 或者代码中创建一个自定义的 HeaderView,然后在 TableView 的代理方法中返回它。 ### 在 XIB 中创建自定义 HeaderView 在 XIB 中创建自定义 HeaderView 的方法非常简单,我们只需要创建一个新的 XIB 文件,然后在 XIB 中添加一个 UIView,将它的 Class 设置为 UITableViewHeaderFooterView,接着就可以在 XIB 中自定义 HeaderView 的内容和样式了。 创建完成后,我们需要在代码中注册这个 XIB 文件,并且设置它的重用标识符。在 TableView 的初始化方法中,我们可以通过以下方法来注册 XIB 文件: ``` UINib *headerNib = [UINib nibWithNibName:@"HeaderView" bundle:nil]; [tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码中,我们首先通过 `nibWithNibName:bundle:` 方法加载 XIB 文件,然后通过 `registerNib:forHeaderFooterViewReuseIdentifier:` 方法注册 XIB 文件,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法中,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; return headerView; } ``` ### 在代码中创建自定义 HeaderView 在代码中创建自定义 HeaderView 的方法也非常简单,我们只需要创建一个继承自 UITableViewHeaderFooterView 的类,然后在这个类中实现自定义 HeaderView 的内容和样式。 ``` @interface CustomHeaderView : UITableViewHeaderFooterView @property (nonatomic, strong) UILabel *titleLabel; @end @implementation CustomHeaderView - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithReuseIdentifier:reuseIdentifier]) { self.contentView.backgroundColor = [UIColor grayColor]; self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.contentView.bounds.size.width - 20, self.contentView.bounds.size.height)]; self.titleLabel.font = [UIFont systemFontOfSize:16]; self.titleLabel.textColor = [UIColor whiteColor]; [self.contentView addSubview:self.titleLabel]; } return self; } @end ``` 上面的代码中,我们创建了一个名为 `CustomHeaderView` 的类,继承自 UITableViewHeaderFooterView。在这个类的初始化方法中,我们设置了 HeaderView 的背景颜色,并且创建了一个 UILabel 来显示标题,最后将它添加到 HeaderView 的 contentView 上。 创建完成后,我们需要在代码中注册这个自定义 HeaderView,并且设置它的重用标识符。在 TableView 的初始化方法中,我们可以通过以下方法来注册自定义 HeaderView: ``` [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码中,我们通过 `registerClass:forHeaderFooterViewReuseIdentifier:` 方法注册自定义 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法中,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; CustomHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; headerView.titleLabel.text = [NSString stringWithFormat:@"Header %ld", section]; return headerView; } ``` 上面的代码中,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取自定义的 HeaderView,并且设置它的标题为 `Header section`。最后,我们返回自定义的 HeaderView。 总结 在本文中,我们介绍了如何在 TableView 中循环利用 HeaderView,并且还介绍了如何自定义 HeaderView。循环利用 HeaderView 可以提高 TableView 的性能,自定义 HeaderView 可以让我们更加灵活地控制 HeaderView 的样式和内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值