Masonry + UIScrollView 之上下滚动

    作为iOS初学者,习惯了用frame来写控件位置,随着往下学习,接触到自动布局的使用,然后发现用frame写,会出现一系列问题。接着我改变以前的习惯,慢慢学习自动布局,适应用自动布局代替frame的使用。在网上找各种资料,随后在找到不错的masonry学习文章,各位可以看看这篇iOS Autolayout之Masonry解读,应该对初学者有用。


Masonry + UIScrollView使用:

    这是我在学习自动布局的时候遇到过的问题,当时界面写完,加上布局,不会滚动?当时心里想,“挖槽,什么情况”,然后在网上查找资源解决问题.



刚开始写完是这样的不会滑动的:


不会滚动界面.

绿色是View,准备在上面放UIButton的,然后不会滑动就没添加。



然后我参考网上的资料,我发现自己错误:


给了ContenSize设置了太小....(其实当时在masonry不知道怎么设置)





然后在网上发现大神们,根本没有设置ContenSize的大小,为什么会滚动呢?

原来把自定义的View添加到scrollView上时,它的大小就是scrollView的contenSize的大小了!!

接着把所有的控件都添加到这个view上,然后使自定义View底部约束  等于  自定义View里面的最后一个控件底部约束。




第一步:

    self.scrollview = [[UIScrollView alloc] init];  

  self.scrollview.backgroundColor = [UIColor clearColor];        self.scrollview.showsVerticalScrollIndicator = NO; 

  //增加额外的滚动区域   

//self.scrollview.contentInset  = UIEdgeInsetsMake(-20, 0, 44, 0);   

// 去掉弹簧效果

//    self.scrollview.bounces = NO; 

  [self.view addSubview:self.scrollview];     

  // UIScrollView 对四边left top bottom right 进行约束,值均为0,作为view 的子视图存在    [self.scrollview mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.left.bottom.right.equalTo(self.view); 

  }];


第二步:

//自定义的View  

  //UIScrollView 新增一个名为v1 视图UIView,同样对其四边约束,添加width 相对父视图进行宽度约束。(关键的一步。需要为UIScrollView 添加一个子视图)   

//v1 的高度内容,决定 这个滚动条会不会上下滚动,影响contentSize 

  UIView *v1 = [[UIView alloc] init]; 

  v1.backgroundColor = [UIColor grayColor];

    [self.scrollview addSubview:v1];

    [v1 mas_makeConstraints:^(MASConstraintMaker *make) {        make.edges.equalTo(self.scrollview);        //上下滚动        make.width.equalTo(self.scrollview);     

  /*         和下面的效果一样       

make.top.mas_equalTo(self.scrollView.mas_top).offset(0);        make.left.mas_equalTo(self.scrollView.mas_left).offset(0);        make.right.mas_equalTo(self.scrollView.mas_right).offset(0);        make.bottom.mas_equalTo(self.scrollView.mas_bottom).offset(0);      

          */

    }];    


第三步(重要的一步):


//v1最后一个控件

         UIButton *btn2 = [[UIButton alloc] init];   

btn2.titleLabel.textColor = [UIColor whiteColor]; 

  btn2.backgroundColor = [UIColor blackColor]; 

  [btn2 setTitle:@"点击报名" forState:UIControlStateNormal];  

     [v1 addSubview:btn2];

//添加btn2的约束

    [btn2 mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.mas_equalTo(laba9.mas_bottom).offset(50);        make.centerX.mas_equalTo(v1);     

  make.width.and.height.mas_equalTo(80);  

         }];

    //使自定义View底部等于最后一个控件设置的底部约束。   

[v1 mas_makeConstraints:^(MASConstraintMaker *make) {   

    make.bottom.equalTo(btn2.mas_bottom); 

  }];

你会注意上面的代码 [v1 mas_makeConstraints…]使用了两次..

这是没有错的..虽然v1对象是一样的..但约束是不一样的.

第一个是对scrollview 的..第二个是对btn2的.

PS:v1这个视图是来设置scrollView的contenSize的大小的.

引用它来实现scrollView的滚动.


可以参考一下:

Demo



如果有哪里错误指出,望大神指出.



你可能感兴趣的:(Masonry + UIScrollView 之上下滚动)