Disabling vertical scrolling in UIScrollView

后端 未结 12 1947
终归单人心
终归单人心 2020-11-30 20:02

There is an option in IB to uncheck vertical scrolling on a scrollview, but it doesnt seem to work.

How can the scrollview be set to only scroll horizontally, and no

相关标签:
12条回答
  • 2020-11-30 20:37

    You need to pass 0 in content size to disable in which direction you want.

    To disable vertical scrolling

    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width,0);
    

    To disable horizontal scrolling

    scrollView.contentSize = CGSizeMake(0,scrollView.contentSize.height);
    
    0 讨论(0)
  • 2020-11-30 20:39

    Include the following method

    -(void)viewDidLayoutSubviews{
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    

    and set the content size width of the scroll view equal to the width of the scroll view.

    0 讨论(0)
  • 2020-11-30 20:42

    since iOS7:

    first: the content size width must be equal to the width of your scrollview

    second: in your initWithNibName:

    self.automaticallyAdjustsScrollViewInsets = NO;
    

    That´s it.

    0 讨论(0)
  • 2020-11-30 20:44

    I updated the content size to disable vertical scrolling, and the ability to scroll still remained. Then I figured out that I needed to disable vertical bounce too, to disable completly the scroll.

    Maybe there are people with this problem too.

    0 讨论(0)
  • 2020-11-30 20:45

    A lot of answers include setting the contentOffset to 0. I had a case in which I wanted the view inside the scrollView to be centered. This did the job for me:

    public func scrollViewDidScroll(_ scrollView: UIScrollView) {
        scrollView.contentOffset.y = -scrollView.contentInset.top
    }
    
    0 讨论(0)
  • 2020-11-30 20:46

    yes, pt2ph8's answer is right,

    but if for some strange reason your contentSize should be higher than the UIScrollView, you can disable the vertical scrolling implementing the UIScrollView protocol method

     -(void)scrollViewDidScroll:(UIScrollView *)aScrollView;
    

    just add this in your UIViewController

    float oldY; // here or better in .h interface
    
    - (void)scrollViewDidScroll:(UIScrollView *)aScrollView
    {
        [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, oldY)];
        // or if you are sure you wanna it always on top:
        // [aScrollView setContentOffset: CGPointMake(aScrollView.contentOffset.x, 0)];
    }
    

    it's just the method called when the user scroll your UIScrollView, and doing so you force the content of it to have always the same .y

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