0

I want to stop backward scrolling on ScrollView after user scrolls to the next page. How can I do that.

I tried the following two codes, but the first one does not have any effect

 self.scrollView.contentOffset  = CGPointMake(self.view.frame.width,0)

and the second only disables the forward scrolling.

self.scrollView.contentSize =  CGSizeMake( 2 * scrollWidth, scrollHeight);
  • http://stackoverflow.com/questions/5095713/disabling-vertical-scrolling-in-uiscrollview - answer here disables vertical scroll. –  Dec 11 '16 at 04:58

2 Answers2

1

To disable scrolling in one direction you implement the UIScrollViewDelegate method scrollViewDidScroll and put your logic there. For instance this TableViewController can only ever scroll down, because if the user tries to scroll up, we just overwrite the contentOffset, effectively undoing their scroll before they see it.

    class ViewController: UITableViewController {
        var lastScrollPosition = CGPoint.zero
        override func scrollViewDidScroll(_ scrollView: UIScrollView) {
            guard scrollView.contentOffset.y > lastScrollPosition.y else {
                scrollView.setContentOffset(lastScrollPosition, animated: false)
                return
            }
            lastScrollPosition = scrollView.contentOffset
        }
    }
Josh Homann
  • 15,933
  • 3
  • 30
  • 33
1

If your cell is equal in size to your screen, you can apply the following option, which is very smooth:

var lastScrollPosition = CGPoint.zero
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.x == lastScrollPosition.x + UIScreen.main.bounds.width {
        lastScrollPosition.x += UIScreen.main.bounds.width
    }
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
    guard scrollView.contentOffset.x > lastScrollPosition.x else {
        scrollView.setContentOffset(lastScrollPosition, animated: false)
        return
    }
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83