UITableview的高级编辑

2016-07-31  本文已影响51人  沙长健

要如何实现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
}
上一篇下一篇

猜你喜欢

热点阅读