Restrict scrolling direction

suggest change

You can restrict the directions the user is able to scroll to using the following code:

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.x != 0 {
        scrollView.contentOffset.x = 0
    }
}

Every time the user scrolls on the x-axis, the scrollView’s content offset is set back to 0.

You can obviously change the xs to ys and therefor lock the direction to be horizontal-only.

You also need to make sure you put this code into the scrollViewDidScroll(_ scrollView: UIScrollView) delegate method. Otherwise, you won’t get it to work.

Also, be sure to have imported the UIScrollViewDelegate in your class declaration, like so:

class ViewController: UIViewController, UIScrollViewDelegate

…and set the scrollView’s delegate to self in some method like viewDidLoad(_:)

scrollView.delegate = self

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents