3

As the question title says, is it possible to enable paging in UIScrollView only for one direction?

I have a UIScrollView that scrolls in both x and y directions, but I want only one direction to be paginated, is this possible?

The only solution that came in my mind is to have another UIScrollView inside the first, is this the only solution?

Janmenjaya
  • 4,149
  • 1
  • 23
  • 43
allemattio
  • 1,836
  • 17
  • 33
  • This sounds like a very complicated design. Have you considered other approaches? such as breaking your UI up into tableViewCells? and having only one (or more) of those horizontally scroll? – Simon McLoughlin Sep 19 '16 at 10:10
  • I can't use TableViews, the design is too complex. I have to use scrollviews – allemattio Sep 19 '16 at 10:18

2 Answers2

1

You should implement scrollViewWillBeginDecelerating delegate method ofUIScrollview`.

You should store current content offset somewhere.

then compare y of your scrollview's current content offset and last stored with content offset. If current y is greater then scroll direction is up side and if last stored y is greater then direction is down side. Now if you want paging effect on up direction only then when you detect up direction set new content offset to your scrollview. for example if current y offset is 0 then set it to y+screenheight.

You can refer this so post for some guidance to manage what i have said!

Community
  • 1
  • 1
Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
1

This is how I solved it:

First, set to set your scrollView's delegate, which could look like:

scrollView.delegate = self

And then

var lastOffsetY: CGFloat = 0
var lastOffsetX: CGFloat = 0

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y != lastOffsetY {
        lastOffsetY = scrollView.contentOffset.y
        scrollView.isPagingEnabled = false
    } else {
        scrollView.isPagingEnabled = true
    }
    if scrollView.contentOffset.x != lastOffsetX {
        lastOffsetX = scrollView.contentOffset.x
        scrollView.isPagingEnabled = true
    } else {
        scrollView.isPagingEnabled = false
    }
}

This will make only it pageable in horizontal direction. For vertical direction just flip the true/false values.

Michal Šrůtek
  • 1,647
  • 16
  • 17
nullforlife
  • 1,354
  • 2
  • 18
  • 30