iOS UIScrollView Restrict scrolling direction

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any iOS Question?