UITableview的高级编辑

要如何实现tableView的多选呢下面我总结了一下,只需要实现四个方法就能实现cell的多选模式
首先tableView的必须实现的协议方法不包含在四个方法里面,其中一个是UIViewcontroller里的方法,并不是协议方法.但是执行此方法会有一个bug,当你提交两种style时(在第二个实现方法中)不能实现滑动删除.
其中第一个方法是UIViewcontroller的方法 设置可编辑模式

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [_tableView setEditing:editing animated:animated];
    if (editing) {
    // no done
    } else {
    // delete selected array   
    [array removeObjectsInArray:_selectedArray]; // selected component added array
   [_tableView deleteRowsAtIndexPaths:_selectedIndexArray  withRowAnimation:UITableViewRowAnimationLeft]; // selected indexPath added array
       [_selectedIndexArray removeAllObjects];  // empty array component
       [_selectedArray removeAllObjects];   // empty array component
    }
}

第二个实现方法UITableViewdelegate 返回style

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
   // selected deleteStyle and insertStyle at the same time 
    return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;
}

第三个实现方法UITableViewdelegate 方法功能是选中

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.editing) {
       [_selectedIndexArray addObject:indexPath];  // add indexPath to array 
       [_selectedArray addObject:_array[indexPath.row]];// add component to array
    }
}

第四个实现方法是UITableViewdelegate 方法是取消

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.editing) {
        [_selectedArray removeObject:_array[indexPath.row]]; // delete selected component
        [_selectedIndexArray removeObject:indexPath]; // delete selected indexPath
    }
}

另外怎样实现单个cell的多功能呢,下面的方法能够解决此问题

- (nullable NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {    
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [_nameArr removeObjectAtIndex:indexPath.row];
        [_tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }];
    return @[rowAction];  // can add more rowAction to complete other operation
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,200评论 4 61
  • 概述在iOS开发中UITableView可以说是使用最广泛的控件,我们平时使用的软件中到处都可以看到它的影子,类似...
    liudhkk阅读 9,086评论 3 38
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,205评论 30 471
  • 一如生活低沉的时候,总想在书中找到些许慰藉。原来以为《活着》会和《平凡的世界》大概是一种路线调子,没想到平凡的世界...
    范瑜曦阅读 359评论 0 2
  • 这里的围墙太高 我看不到天空 我想着我的小旅馆 隔壁的沙滩 但没有回忆 城墙倒了 啤酒凉了 墙外的...
    猫九河阅读 208评论 0 1