【译】UICollectionView 轻松重排
我超喜欢 最简单的实现重排是通过使用 func collectionView(collectionView: UICollectionView,moveItemAtIndexPath sourceIndexPath: NSIndexPath,toIndexPath destinationIndexPath: NSIndexPath) { // move your data order // 可以留空 } 当前的 collection view 判定 items 可以被移动,因为
当我们希望在一个简单的 override func viewDidLoad() { super.viewDidLoad() longPressGesture = UILongPressGestureRecognizer(target: self,action: "handleLongGesture:") self.collectionView.addGestureRecognizer(longPressGesture) } func handleLongGesture(gesture: UILongPressGestureRecognizer) { switch(gesture.state) { case UIGestureRecognizerState.Began: guard let selectedIndexPath = self.collectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else { break } collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath) case UIGestureRecognizerState.Changed: collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(gesture.view!)) case UIGestureRecognizerState.Ended: collectionView.endInteractiveMovement() default: collectionView.cancelInteractiveMovement() } } 我们保存了在 long press gesture 中不活的被选中的 index path 并且基于它是否有值决定允不允许拖动手势生效。然后,我们根据手势状态调用一些新的 collection view 方法。
这些让搞定拖动手势非常容易。
效果和标准的
嗯,看起来不错,不过如果我们不想在移动的时候改变 cell 大小呢?选中的 cell 大小应该在交互移动时保持一致。这是可以实现的。 func invalidationContextForInteractivelyMovingItems(targetIndexPaths: [NSIndexPath],withTargetPosition targetPosition: CGPoint,previousIndexPaths: [NSIndexPath],previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext func invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths(indexPaths: [NSIndexPath],movementCancelled: Bool) -> UICollectionViewLayoutInvalidationContext 前一个在目标 indexPath 和之前的 indexPath 之间进行移动时调用。另一个类似,不过是在移动结束之后调用。有了这些我们就可以通过一些小手段达到我们的要求。 internal override func invalidationContextForInteractivelyMovingItems(targetIndexPaths: [NSIndexPath],previousPosition: CGPoint) -> UICollectionViewLayoutInvalidationContext { var context = super.invalidationContextForInteractivelyMovingItems(targetIndexPaths,withTargetPosition: targetPosition,previousIndexPaths: previousIndexPaths,previousPosition: previousPosition) self.delegate?.collectionView!(self.collectionView!,moveItemAtIndexPath: previousIndexPaths[0],toIndexPath: targetIndexPaths[0]) return context } 解决方案非常清晰。获取正在移动的 cell 之前和目标 index path。然后调用
不用怀疑,collection view 重排是一个非常棒的更新。UIKit 工程师干得太棒了!:) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |