allemattio
allemattio

Reputation: 1848

iOS make UIScrollView paging enabled only for one direction

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?

Upvotes: 3

Views: 1224

Answers (2)

nullforlife
nullforlife

Reputation: 1414

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.

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27428

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!

Upvotes: 1

Related Questions