【问题标题】:UICollectionView change Drop Placeholder index pathUICollectionView 更改 Drop Placeholder 索引路径
【发布时间】:2019-09-17 08:17:27
【问题描述】:

我想使用拖放实现以下 UX。简介:用户应该只能在末尾插入一个项目。

  1. 用户可以从任何来源拖动项目并将其指向集合视图。
  2. 当项目挂在视图上方时,占位符出现在特定位置,例如最后。
  3. 当用户释放项目时,它会根据占位符的索引进行动画处理。

我可以采用UICollectionViewDropDelegate实现步骤3:

func collectionView(
    _ collectionView: UICollectionView,
    performDropWith coordinator: UICollectionViewDropCoordinator) {

    // ...
    coordinator.drop(item, toItemAt: endIndexPath)
}

问题是改变占位符索引,默认在拖拽项下。我们可以使用collectionView(_:dropSessionDidUpdate:withDestinationIndexPath destinationIndexPath:) 提供建议。但是UICollectionViewDropProposal中没有指定索引路径的变量。

【问题讨论】:

    标签: ios swift uicollectionview drag-and-drop


    【解决方案1】:

    尝试使用collectionView(_:targetIndexPathForMoveFromItemAt:toProposedIndexPath:)。虽然它不是最后一个索引,但返回 originalIndexPath。

    func collectionView(_ collectionView: UICollectionView, targetIndexPathForMoveFromItemAt originalIndexPath: IndexPath, toProposedIndexPath proposedIndexPath: IndexPath) -> IndexPath {        
        guard proposedIndexPath.item == lastItemIndex // Here should be some logic to calculate the last index
            else { return originalIndexPath }
        return proposedIndexPath
    }
    

    但是,对于某些实现,此函数永远不会被调用。例如,当您使用 UICollectionViewController 时。在这种情况下,在删除时返回 .cancel 提案 — UICollectionViewDropProposal(operation: .cancel, intent: .insertAtDestinationIndexPath)collectionView(_:dropSessionDidUpdate:withDestinationIndexPath:) 函数中:

    func collectionView(_ collectionView: UICollectionView,
      dropSessionDidUpdate session: UIDropSession,
      withDestinationIndexPath destinationIndexPath: IndexPath?)
      -> UICollectionViewDropProposal {
    
        guard destinationIndexPath?.item != lastItemIndex // Here should be some logic to calculate the last index
        else {
            return UICollectionViewDropProposal(
             operation: .cancel,
             intent: .insertAtDestinationIndexPath)
        }
      return UICollectionViewDropProposal(
        operation: .move,
        intent: .insertAtDestinationIndexPath)
    }
    

    【讨论】:

    • 稍后我会测试你的答案并给出一些有意义的反馈。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多