首页 > 技术文章 > ScrollView设置了ContentSize高度为0,仍然能滑动的问题

pengsi 2017-03-03 09:28 原文

 你有没有遇到过这样的情况:

对于ScrollView的不能上下滑动,设置了以下代码:

 _scrollViewTitle=[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, TitleHeight)];

 _scrollViewTitle.contentSize = CGSizeMake(_titleArray.count*btnWidth, 0);

 

可是....ScrollView仍然能够滑动...你一定检查了创建和设置ScrollView的代码很多遍,还是发现不了问题..哈哈,我也一样...

 

 

其实解决方法很简单: 看代码:

- (void)initcategroyScrollView{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _scrollViewTitle = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kWidth, TitleHeight)];
    _scrollViewTitle.delegate = self;
    _scrollViewTitle.tag = 100;
    _scrollViewTitle.bounces = NO;
    _scrollViewTitle.backgroundColor = [UIColor greenColor];
     _scrollViewTitle.showsVerticalScrollIndicator = YES;
    _scrollViewTitle.showsHorizontalScrollIndicator = YES;
    _scrollViewTitle.alwaysBounceVertical = NO;  // 默认是NO
    _scrollViewTitle.directionalLockEnabled =YES;//禁止同时左右和上下滚动
    [self.view addSubview:_scrollViewTitle];
    _scrollViewTitle.contentSize = CGSizeMake(_titleArray.count*btnWidth, 0);
    for (int i = 0; i < _titleArray.count; i++) {
        UIButton*btn = [[UIButton alloc]initWithFrame:CGRectMake(btnWidth*i, 0, btnWidth, TitleHeight)];
        [btn setBackgroundColor:[UIColor whiteColor]];
        btn.tag =20+i;
        btn.enabled = NO;
        [btn setTitle:_titleArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollViewTitle addSubview:btn];
        if (i==0) {
            _index=20+i;
           [btn setTitleColor:Main_Color forState:UIControlStateNormal];
        }
    }
     _lineView = [[UIView alloc]initWithFrame:CGRectMake(0, TitleHeight-1, btnWidth, 1)];
    _lineView.tag=30;
    _lineView.backgroundColor = [UIColor redColor];
    [_scrollViewTitle addSubview:_lineView];
}

总结:

设置代码 self.automaticallyAdjustsScrollViewInsets = NO;即可

  • automaticallyAdjustsScrollViewInsets是ViewController的一个属性,指示VIewController是否需要自动调整ScrollViewInsets。
  • 默认值为YES,允许ViewController自动调整ScrollViewInsets ##VC对ScrollView的调整
  • 当automaticallyAdjustsScrollViewInsets值为YES时,viewController根据当前view中statusBar,navigaionTionBar,toolBar或者toolBar来自动调整scrollView的的contentInset和ContentOffset。使得scrollView的内容不会被这些Bar遮挡

其实还是不怎么懂automaticallyAdjustsScrollViewInsets和scrollView的滑动有啥关系呢???有懂的大神留言告诉我哟..很感谢...嘿嘿

推荐阅读