iOS UIScrollView使用Autolayout

  最近项目在迭代更新的时候,需要在之前用Autolayout写的界面里添加一个button,添加完这个button后,iPhone5,iPhone4显示不全了.遇到整个问题后很自然就想到了用UIScrollView,很快就创建了一个占满全屏的UIScrollView,把之前所有的控件有[self.view addSubview:xxx]全部改成[self.scrollView addSubview:xxx],信心满满的点击了一个运行按钮,艹,居然滑动不了......

  重新调整了一下思路,解决了此问题,先创建一个UIScrollView没错,然后创建一个contrainerView用于存储之前添加在[self.view]上的控件,把contrainer再添加到scrollview上,最后调整contrainerView的位置即可.

  代码:

// 创建一个scrollview
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:scrollView];
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

    // 创建一个view,这个view里面放置各种view控件,并添加到scrollview上
    UIView *contrainerView = [[UIView alloc] initWithFrame:CGRectZero];
    [scrollView addSubview:contrainerView];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectZero];
    view1.backgroundColor = [UIColor redColor];
    [contrainerView addSubview:view1];
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@20);
        make.right.equalTo(@(-20));
        // 宽度不写view显示不出来
        make.width.equalTo(@(self.view.frame.size.width - 40));
        make.height.equalTo(@200);
    }];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectZero];
    view2.backgroundColor = [UIColor greenColor];
    [contrainerView addSubview:view2];
    [view2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@100);
        make.top.equalTo(view1.mas_bottom).offset(10);
        make.right.equalTo(@(-100));
        // 宽度不写view显示不出来
        make.width.equalTo(@(self.view.frame.size.width - 200));
        make.height.equalTo(@400);
    }];

    UIView *view3 = [[UIView alloc] initWithFrame:CGRectZero];
    view3.backgroundColor = [UIColor redColor];
    [contrainerView addSubview:view3];
    [view3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.top.equalTo(view2.mas_bottom).offset(10);
        make.right.equalTo(@(-20));
        // 宽度不写view显示不出来
        make.width.equalTo(@(self.view.frame.size.width - 40));
        make.height.equalTo(@200);
    }];

    // 容器的顶部位置基于最后一个view控制来确定
    [contrainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(scrollView);
        make.bottom.equalTo(view3.mas_bottom).offset(20);
    }];

 

  如果你不是在wb145230博客园看到本文,请点击查看原文.

转载于:https://www.cnblogs.com/wb145230/p/5259127.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值