UIScrollView AND AutoLayout

dowhilenet

您可以先看看这篇文章,因为我也是从这里了解到的一点点。

介绍用代码来完成ScrollView的AutoLayout布局,用到了一个十分好用的第三方库SnapKit

整个思路呢就使用一个容器来包括所有的原本ScrollView的子视图,最终通过容器的大小来确定ScrollViewcontentSize

Show Your Code

import UIKit
import SnapKit


class ScrollViewAutoLayoutViewController: UIViewController {
    
    let ScreenWidth = UIScreen.mainScreen().bounds.width

    let scroolView = UIScrollView()
    let containerView = UIView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        layoutWithContainer()
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension ScrollViewAutoLayoutViewController {
    func layoutWithContainer() {
        
        scroolView.backgroundColor = UIColor.yellowColor()
        view.addSubview(scroolView)
        //设置 ScrollView 约束
        scroolView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
        
        containerView.backgroundColor = UIColor.blueColor()
        scroolView.addSubview(containerView)
        //设置 容器视图的约束 (宽度确定了,高度还没有确定)
        containerView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(scroolView)
            make.width.equalTo(ScreenWidth)
        }
        
        //给容器视图添加子视图
        for i in 0...10 {
            let box = UIView()
            box.backgroundColor = .redColor()
            containerView.addSubview(box)
            //子视图的约束
            box.snp_makeConstraints(closure: { (make) -> Void in
                make.leading.trailing.equalTo(containerView)
                make.height.equalTo(ScreenWidth)
                if i == 0 {
                    make.top.equalTo(containerView).offset(10)
                }else {
                    let previewBox = containerView.subviews[i - 1] as UIView
                    make.top.equalTo(previewBox.snp_bottom).offset(30)
                }
                
                if i == 10 {
                //这条约束使得整个容器视图的高度也就确定了
                   make.bottom.equalTo(containerView).offset(-30)
                }
            })
        }
    }
}
阅读 2.4k

这块显卡有点冷
迷茫的程序员的成长之路
654 声望
10 粉丝
0 条评论
654 声望
10 粉丝
文章目录
宣传栏