How to disable vertical scrolling in UIScrollView

2019-04-07 15:17发布

I want to disable vertical scrolling from my UIScrollView if possible.. My code is like below.. Working fine except users can scroll up and down which shouldn't be there I believe.. Thanks in advance..

    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, self.view.frame.size.width, self.view.frame.size.height / 3)];   
    scroll.contentSize = CGSizeMake(scroll.contentSize.width,scroll.frame.size.height); 
    scroll.pagingEnabled = YES;
    scroll.backgroundColor = [UIColor blackColor];
    int xVal = 30;

    NSInteger numberOfViews = 5;
    for (int i = 0; i < numberOfViews; i++) {
        UILabel *testLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(xVal, 0, 90, 100)];
        UILabel *testLabel2 = [[UILabel alloc] initWithFrame:CGRectMake(xVal, 20, 90, 100)];
        UILabel *testLabel3 = [[UILabel alloc] initWithFrame:CGRectMake(xVal, 40, 90, 100)];

        testLabel2.backgroundColor = [UIColor clearColor];
        testLabel2.text =@"Test1";
        testLabel2.textColor = [UIColor whiteColor];
        testLabel2.font = [UIFont boldSystemFontOfSize:12];

        testLabel1.backgroundColor = [UIColor clearColor];
        testLabel1.text =@"Test2";
        testLabel1.textColor = [UIColor whiteColor];
        testLabel1.font = [UIFont boldSystemFontOfSize:12];

        testLabel3.backgroundColor = [UIColor clearColor];
        testLabel3.text =@"Test3";
        testLabel3.textColor = [UIColor whiteColor];
        testLabel3.font = [UIFont boldSystemFontOfSize:12];

        xVal += 120;

        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(xVal, 30, 150, 130)];
        view.backgroundColor = [UIColor blackColor];

        xVal += 200;

        [scroll addSubview:testLabel1];
        [scroll addSubview:testLabel2];
        [scroll addSubview:testLabel3];
        [scroll addSubview:view];
    }

    [self.view addSubview:scroll];

7条回答
一夜七次
2楼-- · 2019-04-07 15:49

In my situation, I was unable to get the height of the scrollview (due to autolayout, I wasn't able to get the height in viewDidLoad). You can add this to the delegate method.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    self.scrollView.contentOffset = CGPointMake(self.scrollView.contentOffset.x, 0);
}
查看更多
登录 后发表回答