Disabling Horizontal Scrolling from UIScrollView Swift

Like this,

Swift 4.0

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

And, you can set this property:

scrollImg.isDirectionalLockEnabled = true

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

This stops the scrollview from scrolling towards the leading edge too.


I changed this so that it just returns 0. No need to check at all if you want scroll off.

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

No need for the directional lock.


Swift 4

Horizontal Scroll Lock

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

You can change the x to y for vertical scrolling.

Make sure to add UIScrollViewDelegate like this:

class MyViewController: UIViewController, UIScrollViewDelegate {

    @IBOutlet var scrollView: UIScrollView!

    ...
}

And set the delegate for the ScrollView

scrollView.delegate = self