iOS ~ 1、UITableView的cell,上、下移动时使用drag、drop;2、UICollectionView的cell移动位置:

一、UITableView上下移动位置(系统):

1、在UITableView中,我们可以使用- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath;方法来禁止移动某一行。下面的例子是禁止移动最后一行。但是,虽然不能移动最后一行,却可以将其他行移动至最后一行下方。

二、UITableView上下移动位置(系统):

1、第一种:不用drag和drop

代码:

[self.tableView setEditing:YES animated:YES]; // 进入可编辑状态
//默认编辑模式下,每个cell左边有个红色的删除按钮,设置为None即可去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

//是否允许indexPath的cell移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return NO;
    } else {
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
//    dataArray = [self.listModels mutableCopy];
//
//    // 当结束移动时,判断结束时的位置,把移动的元素删除再加到结束的位置
//    if (sourceIndexPath.row < self.listModels.count) {
//
//        GWCityManageListModel *userModel = self.listModels[sourceIndexPath.row];
//        [dataArray removeObjectAtIndex:sourceIndexPath.row];
//
//        if (destinationIndexPath.row >= dataArray.count) {
//            [dataArray addObject:userModel];
//        } else {
//            [dataArray insertObject:userModel atIndex:destinationIndexPath.row];
//        }
//
//    }
//    self.listModels  = [dataArray copy];
//
//    // 改变保存的值
//    [[NSUserDefaults standardUserDefaults] setObject:self.listModels forKey:@"saveSort_CityManage_CityWeather_Arr"];
    
    
    NSLog(@"移动的位置索引 = %ld,\n 将要移动到达的位置索引 == %ld", sourceIndexPath.row, destinationIndexPath.row);
    //更新数据源
}

#pragma mark -- 禁止某一行移动
// 禁止某一行移动,并且禁止其他cell移动到该cell的索引位置(这里禁止移动第一行)
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    
    NSIndexPath *indexPath = nil;
    
    // 要求:第一个cell位置置顶,不可移动,所以当移动其他cell到该位置时,进行下列操作:
    if (proposedDestinationIndexPath.row == 0) {
        indexPath = [NSIndexPath indexPathForRow: 1 inSection: 0];
    } else {
        indexPath = [NSIndexPath indexPathForRow: proposedDestinationIndexPath.row inSection: 0];
    }
    return indexPath;
}
2、第二种,使用 drag和drop

需要遵守和实现UITableViewDragDelegateUITableViewDropDelegate代理和其代理方法:
在UITableView中,我们可以使用- (BOOL) tableView: (UITableView *) tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath方法来禁止移动某一行。下面的例子是禁止移动最后一行。但是,虽然不能移动最后一行,却可以将其他行移动至最后一行下方。
所以需要方法:- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath;来设置。
遵守协议:

    <UITableViewDragDelegate, UITableViewDropDelegate>
//    [self.tableView setEditing:YES animated:YES]; // 进入可编辑状态
    self.tableView.dragDelegate = self; // drag 拖拉代理
    self.tableView.dropDelegate = self; // drop
    self.tableView.dragInteractionEnabled = YES; // 打开拖拽功能
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/375*20, [UIScreen mainScreen].bounds.size.width/375*15, [UIScreen mainScreen].bounds.size.width/375*335, [UIScreen mainScreen].bounds.size.height - k_Height_StatusBar - k_Height_NavContentBar - [UIScreen mainScreen].bounds.size.width/375*(75 + 15)) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = RGBA(248, 249, 250, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.dragDelegate = self; // drag 拖拉代理
    self.tableView.dropDelegate = self; // drop
    self.tableView.dragInteractionEnabled = YES; // 打开拖拽功能
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.backView addSubview:self.tableView];
//默认编辑模式下,每个cell左边有个红色的删除按钮,设置为None即可去掉
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleNone;
}

//是否允许indexPath的cell移动
//是否允许indexPath的cell移动
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) { // 禁止第一行移动
        return NO;
    } else {
        return YES;
    }
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
    
    
    NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
    dataArray = [self.listModels mutableCopy];
    
    // 当结束移动时,判断结束时的位置,把移动的元素删除再加到结束的位置
    if (sourceIndexPath.row < self.listModels.count) {
        
        GWCityManageListModel *userModel = self.listModels[sourceIndexPath.row];
        [dataArray removeObjectAtIndex:sourceIndexPath.row];
        
        if (destinationIndexPath.row >= dataArray.count) {
            [dataArray addObject:userModel];
        } else {
            [dataArray insertObject:userModel atIndex:destinationIndexPath.row];
        }
        
    }
    self.listModels  = [dataArray copy];
    
    
    /**
     连续使用交换位置方法:exchangeObjectAtIndex,
     
    例子: 当前index和index+1交换,一直交换到目标位置
    数组:12345,21345,23145,23415,23451
    移动“1”的位置,前移就是减(index-1),后移就是加(index+1)
     
     // 交换位置:exchangeObjectAtIndex,在这里不使用
     [dataArray exchangeObjectAtIndex:destinationIndexPath.row withObjectAtIndex:sourceIndexPath.row];
     */
    
    
//    // 从数组中读取需要移动行的数据
//    id  object = [dataArray objectAtIndex:fromRow];
//    // 在数组中移动需要移动的行的数据
//    [dataArray removeObjectAtIndex:fromRow];
//    // 把需要移动的单元格数据在数组中,移动到想要移动的数据前面
//    [dataArray insertObject:object atIndex:toRow];
    
    NSLog(@"移动的位置索引 = %ld,\n 将要移动到达的位置索引 == %ld", sourceIndexPath.row, destinationIndexPath.row);
    //更新数据源
}

#pragma mark -- 禁止某一行移动
// 禁止某一行移动,并且禁止其他cell移动到该cell的索引位置(这里禁止移动第一行)
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath {
    
    NSIndexPath *indexPath = nil;
    
    // 要求:第一个cell位置置顶,不可移动,所以当移动其他cell到该位置时,进行下列操作:
    if (proposedDestinationIndexPath.row == 0) {
        indexPath = [NSIndexPath indexPathForRow: 1 inSection: 0];
    } else {
        indexPath = [NSIndexPath indexPathForRow:proposedDestinationIndexPath.row inSection: 0];
    }
    return indexPath;
}

#pragma mark -- <UITableViewDragDelegate>

// 拖拽 预览
- (nullable UIDragPreviewParameters *)tableView:(UITableView *)tableView dragPreviewParametersForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 可以在该方法内使用 贝塞尔曲线 对单元格的一个具体区域进行裁剪
    UIDragPreviewParameters *parameters = [[UIDragPreviewParameters alloc] init];

    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/375*(375 - 48), [UIScreen mainScreen].bounds.size.width/375*(100));
    parameters.visiblePath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:[UIScreen mainScreen].bounds.size.width/375*16];
    parameters.backgroundColor = RGBA(248, 249, 250, 0.3);
    return parameters;
}

- (void)tableView:(UITableView *)tableView dragSessionWillBegin:(id<UIDragSession>)session {
    // 将要 拖拽
    NSLog(@"😁😆");
}

- (void)tableView:(UITableView *)tableView dragSessionDidEnd:(id<UIDragSession>)session {
    // 拖拽 结束
    NSLog(@"😁😆");
}

/**
 当接收到添加item响应时,会调用该方法向已经存在的drag会话中添加item
 如果需要,可以使用提供的点(在集合视图的坐标空间中)进行其他命中测试。
 如果该方法未实现,或返回空数组,则不会将任何 item 添加到拖动,手势也会正常的响应
 */
- (nonnull NSArray<UIDragItem *> *)tableView:(nonnull UITableView *)tableView itemsForBeginningDragSession:(nonnull id<UIDragSession>)session atIndexPath:(nonnull NSIndexPath *)indexPath {
    return nil;
//    return @[[[UIDragItem alloc] initWithItemProvider:[NSItemProvider new]]];
    
//    NSItemProvider *itemProvider = [[NSItemProvider alloc] initWithObject:self.dataSource[indexPath.item]];
//    UIDragItem *item = [[UIDragItem alloc] initWithItemProvider:itemProvider];
//    return @[item];
}

// 确保实现该UITableViewDragDelegate方法,并返回YES。这将确保拖放必须发生在同一个应用程序中。
- (BOOL)tableView:(UITableView *)tableView dragSessionIsRestrictedToDraggingApplication:(id<UIDragSession>)session {
    return YES;
}

#pragma mark -- <UITableViewDropDelegate>
// 松手 预览
- (nullable UIDragPreviewParameters *)tableView:(UITableView *)tableView dropPreviewParametersForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 可以在该方法内使用 贝塞尔曲线 对单元格的一个具体区域进行裁剪
    UIDragPreviewParameters *parameters = [[UIDragPreviewParameters alloc] init];
    
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width/375*(375 - 48), [UIScreen mainScreen].bounds.size.width/375*(100));
    parameters.visiblePath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:[UIScreen mainScreen].bounds.size.width/375*16];
    parameters.backgroundColor = RGBA(248, 249, 250, 0.3);
    return parameters;
}

- (void)tableView:(UITableView *)tableView dropSessionDidExit:(id<UIDropSession>)session {
    
}

- (void)tableView:(UITableView *)tableView dropSessionDidEnd:(id<UIDropSession>)session {
    
}

- (void)tableView:(nonnull UITableView *)tableView performDropWithCoordinator:(nonnull id<UITableViewDropCoordinator>)coordinator {
    
}

二、UICollectionView的cell移动位置:

原理:先删除,再插入(注意:判断最后到达的位置的索引号,是否大于数组的数量,大于的话使用addObject:,小于的话使用:insertObject: atIndex:

WechatIMG342.jpeg

第三方:https://github.com/lxcid/LXReorderableCollectionViewFlowLayout

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容