UICollectionview重新排列图像单元格
问题描述:
我得到了一个带有XX图像/单元格的UICollectionview
,我希望在拖放时让它们交换位置。我正在使用内置重新排序功能,但没有满足我的需求。下面是代码:UICollectionview重新排列图像单元格
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongGesture))
longPressGesture.minimumPressDuration = 0.2
longPressGesture.delaysTouchesBegan = true
cameraRollCollectionView.addGestureRecognizer(longPressGesture)
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
guard let selectedIndexPath = cameraRollCollectionView.indexPathForItem(at: gesture.location(in: cameraRollCollectionView)) else {
break
}
cameraRollCollectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
cameraRollCollectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
cameraRollCollectionView.endInteractiveMovement()
default:
cameraRollCollectionView.cancelInteractiveMovement()
}
}
我基本上只是希望动画只能换移动单元和目标单元格,而不是重新排序的“邻居”之类的附加的图像。
我有它在“背后”的工作与此代码:
func collectionView(_ collectionView: UICollectionView,
moveItemAt sourceIndexPath: IndexPath,
to destinationIndexPath: IndexPath) {
let temp = selectedUIImages[sourceIndexPath.row]
selectedUIImages[sourceIndexPath.row] = selectedUIImages[destinationIndexPath.row]
selectedUIImages[destinationIndexPath.row] = temp
}
答
,当你在一个细胞识别长按你可以创建collectionViewCell的内容查看的副本。然后,您可以使所有单元格都处于静止状态时触摸(touchesMoved)移动,当用户放下它时(touchesEnded),您可以计算该位置的indexPath。当你拥有indexPath时,你可以像你已经做的那样改变职位。
集合视图真的是这里最好的方式吗?我问,因为我有一个应用程序的行为完全符合你的需要(拖动一个正方形并放在另一个正方形上交换它们),但我不使用集合视图;这只是一个观点的网格。我不需要集合视图提供的任何东西。 – matt
如果您对使用库感兴趣,请查看:https://github.com/ra1028/RAReorderableLayout –