iOS - 水平滑动 UICollectionViewCell

raz*_*van 3 swipe ios uicollectionviewcell swift

我有一个 UICollectionView,它看起来像一个 tableView,我希望单元格只能水平滑动。

我已经设法让它们四处移动,但问题是我也可以将它们向上移动,基本上我可以向任何方向移动它们,例如,当您删除它时,我希望它们像 tableViewCell 一样滑动。

最后,我希望能够水平地将一个单元格从屏幕上滑出

我附上了一张集合视图现在看起来如何的图像和一个四处移动的单元格(红色的)

在此处输入图片说明

raz*_*van 5

UIPanGestureRecognizer毕竟我找到了一种方法。所有操作都在单元格上(在单元格类内部)。下面你有适合我的解决方案

var swipeGesture: UIPanGestureRecognizer!
var originalPoint: CGPoint!

func configureCell() {
    setupSwipeGesture()
}

func setupSwipeGesture() {
        swipeGesture = UIPanGestureRecognizer(target: self, action:#selector(swiped(_:)))
        swipeGesture.delegate = self

        self.addGestureRecognizer(swipeGesture)
    }


func swiped(_ gestureRecognizer: UIPanGestureRecognizer) {
let xDistance:CGFloat = gestureRecognizer.translation(in: self).x

        switch(gestureRecognizer.state) {
        case UIGestureRecognizerState.began:
            self.originalPoint = self.center
        case UIGestureRecognizerState.changed:
            let translation: CGPoint = gestureRecognizer.translation(in: self)
            let displacement: CGPoint = CGPoint.init(x: translation.x, y: translation.y)

            if displacement.x + self.originalPoint.x < self.originalPoint.x {
                self.transform = CGAffineTransform.init(translationX: displacement.x, y: 0)
                self.center = CGPoint(x: self.originalPoint.x + xDistance, y: self.originalPoint.y)
            }
        case UIGestureRecognizerState.ended:
            let hasMovedToFarLeft = self.frame.maxX < UIScreen.main.bounds.width / 2
            if (hasMovedToFarLeft) {
                removeViewFromParentWithAnimation()
            } else {
                resetViewPositionAndTransformations()
            }
        default:
            break
        }
    }

func resetViewPositionAndTransformations(){
        UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: UIViewAnimationOptions(), animations: {
            self.center = self.originalPoint
            self.transform = CGAffineTransform(rotationAngle: 0)
        }, completion: {success in })
    }

func removeViewFromParentWithAnimation() {
        var animations:(()->Void)!
        animations = {self.center.x = -self.frame.width}

        UIView.animate(withDuration: 0.2, animations: animations , completion: {success in self.removeFromSuperview()})
    }
Run Code Online (Sandbox Code Playgroud)