How do I stop a UIScrollView from bouncing horizontally?

后端 未结 11 1773
名媛妹妹
名媛妹妹 2021-02-05 12:07

I have a UIScrollView that shows vertical data, but where the horizontal component is no wider than the screen of the iPhone. The problem is that the user is still able to drag

相关标签:
11条回答
  • 2021-02-05 12:22

    Make sure the UIScrollView's contentSize is not wider than the UIScrollView itself. In my own apps this was enough to avoid horizontal scrolling, except in cases where I got really crazy swiping in random directions (e.g., starting a scroll while the view was still decelerating).

    0 讨论(0)
  • 2021-02-05 12:23

    That's strange, because whenever I create a scroll view with frame and content size within the bounds of the screen on either dimension, the scroll view does not scroll (or bounce) in that direction.

    // Should scroll vertically but not horizontally
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    scrollView.contentSize = CGSizeMake(320, 1000);
    

    Are you sure the frame fits completely within the screen and contentSize's width is not greater than the scroll view's width?

    0 讨论(0)
  • 2021-02-05 12:23

    The checkbox for bounce vertically in storyboard-scrollview can simply help...

    enter image description here

    0 讨论(0)
  • 2021-02-05 12:25

    Whether or not a view scrolls (and bounces) horizontally depends on three things:

    • The content size
    • The left and right content insets
    • The width of the scroll view -

    If the scroll view can fit the content size plus the insets then it doesn't scroll or bounce.

    Avoid horizontal bouncing like so:

    scrollView.contentSize = CGSizeMake(scrollView.frame.size.width - scrollView.contentInset.left - scrollView.contentInset.right, height);
    

    I am adding this answer because the previous ones did not take contentInset into account.

    0 讨论(0)
  • 2021-02-05 12:36
    scrollView.bounces = NO;
    

    Worked for me.

    0 讨论(0)
提交回复
热议问题