iphoneiosipaduiscrollviewscroll

UIScrollView scrolling in only one direction at a time


I have a UIScrollView and I want it to be able to scroll in both directions (it currently does) but only one at a time. So, for instance, if you start scrolling it horizontally, it won't move vertically at all until you let go and start moving it vertically. How could I go about doing this?


Solution

  • Set the isDirectionalLockEnabled property to true. From the Apple docs:

    If this property is false, scrolling is permitted in both horizontal and vertical directions. If this property is true and the user begins dragging in one general direction (horizontally or vertically), the scroll view disables scrolling in the other direction. If the drag direction is diagonal, then scrolling doesn’t lock and the user can drag in any direction until the drag completes. The default value is false.

    Note that

    1. This works perfectly as of 2024, iOS17

    2. In the distant past, it was buggy. It now works.

    3. You DO NOT have to manually override didScroll or anything else, isDirectionalLockEnabled now works perfectly.

    4. Note that the description of isDirectionalLockEnabled in the Xcode quick help, is, completely wrong. The actual "discussion" from the doc, quoted above, is correct.

    5. HOWEVER note that, BY DESIGN, Apple has a weird feature, where if the user drags slowly and at a 45° angle, then in fact the user CAN scroll "freehand", and there is no direction lock. (This is what is explained in the @Ash answer.) If you want a true one-at-a-time scroll, you have to program it, which with modern iOS is very simple. (Watch out for very old code samples, which now do not work.)