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:


UIScrollView:
* Restrict scrolling direction

Table Of Contents
12 UIView
15 UIColor
26 UIImage
28 CALayer
30 NSDate
34 UIScrollView
40 iBeacon
49 NSTimer
79 NSURL
87 AWS SDK
96 NSData
101 Segues
104 EventKit
105 NSBundle
106 SiriKit
111 StoreKit
117 3D Touch
119 Keychain
122 Block
141 AirDrop
144 UISlider
145 Carthage
146 HealthKit
151 plist
157 MVVM
164 UIPhoenix
166 Simulator
168 NSArray
169 OpenGL
175 Core Data
179 MyLayout
180 UIFont
189 Security
200 Codable