Swipe only to the left using a UIScrollView

323 Views Asked by At

I have a scrollView with the delegate method set.

private let scrollView: UIScrollView = {

    let scrollView = UIScrollView(frame: .zero).usingAutoLayout()
    scrollView.isPagingEnabled = true
    scrollView.showsVerticalScrollIndicator = false
    scrollView.showsHorizontalScrollIndicator = false

    return scrollView
}()

I'm trying to making only scroll to the left to mimic a "delete cell", like in the phone book. I don't want the user to be able to scroll to the right. I have this, which kinda works:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

     if scrollView.contentOffset.x < 0 {

        scrollView.contentOffset.x = 0
}

The problem is that if I swipe fast the contentOffSet is set to positive values, which makes the scrollView scroll in the opposite direction. This usually happens after I finish the swipe gesture. This makes me think it has to do with the bounce, but even setting it to false, it still occurs.

1

There are 1 best solutions below

0
bruno On

Was able to come up with a solution:

extension SwipeableCollectionViewCell: UIScrollViewDelegate {

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {

        if scrollView.panGestureRecognizer.translation(in: scrollView.superview).x > 0 {

            self.scrollDirection = .rigth

        } else {

            self.scrollDirection = .left
        }
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {

        if self.scrollDirection == .rigth {

            scrollView.contentOffset.x = 0
        }
    }
}

private enum ScrollDirection {

    case rigth
    case left
}