我想构建一个 UICollectionView,或使用类似的库来制作 GridView ,我可以在其中重新排列单元格。我的应用程序支持 iOS 7,不幸的是 UICollectionView
方法 - (BOOL)beginInteractiveMovementForItemAtIndexPath:(NSIndexPath *)indexPath
仅适用于 iOS 9 及更高版本。
有什么方法可以在 iOS7 上实现“拖动并重新排序” Collection View 单元格的效果?谢谢。
最佳答案
好吧,我碰巧遇到了同样的问题,所以让我在此补充两分钱。
为了在重新排列单元格时获得与 UIKit 相同的效果,我采用了或多或少类似的方法,如下所述:
将长按手势识别器添加到 Collection View 中,以便 您将能够检测到哪个单元格被窃听而不会弄乱 使用
collectionView:didSelectItemAtIndexPath
方法。当用户长按一个单元格时,截取该单元格的屏幕截图,将快照 View 添加到 Collection View 中,然后隐藏该单元格。当用户在屏幕上移动他的手指时,更新快照的中心以编程方式移动它,这样它看起来就像用户正在拖动单元格。
诀窍是决定何时以及如何交换单元格。随着快照四处移动,它将与其他单元格相交。发生这种情况时,您应该更新数据源并调用
moveItemAtIndexPath
,这样它就会交换原始单元格和快照相交的单元格的位置。拖动结束时,从 Collection View 中移除快照并显示原始单元格。
您可以将这些步骤映射到手势识别器的状态,以便我们知道您在每个状态下应该做什么:
- 开始:1
- 改变:2、3
- 结束、取消、失败:4
我放了一个 example project在我的 github 帐户中,因此您可以下载并使用它。在这里,我将只实现手势回调:
注意:以下代码可能无法运行,因为我丢弃了一些特定于实现的细节。但它应该表明基本意图。请从我的 github 存储库下载完整代码。
func longPressRecognized(recognizer: UILongPressGestureRecognizer) {
let location = recognizer.locationInView(collectionView)
let indexPath = collectionView.indexPathForItemAtPoint(location)
switch recognizer.state {
case .Began:
let cell = collectionView.cellForRowAtIndexPath(indexPath)
let snapshotView = cell.snapshotViewAfterScreenUpdates(true)
snapshot.center = cell.center
collectionView.addSubview(snapshotView)
cell.contentView.alpha = 0.0 // hides original cell
case .Changed:
snapshotView.center = location // will follow user's finger.
dataSource.swap(originalCellIndexPath.item, indexPath.item) // swaps data
collectionView.moveItemAtIndexPath(originalCellIndexPath, toIndexPath: indexPath) // swaps cells
originalCellIndexPath = indexPath
default:
let cell = cellForRowAtIndexPath(originalCellIndexPath)
cell.contentView.alpha = 1.0
snapshotView.removeFromSuperview()
}
}
这是您将获得的效果(在 iOS 8.4 模拟器上记录):
关于ios - 在 iOS7 中重新排序 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36821289/