以编程方式布局UIScrollView,并为其子视图添加了自动布局,但它不滚动

时间:2017-10-05 19:39:57

标签: ios swift uiscrollview

我想弄清楚UIScrollView是如何工作的,我用不同的backgroundColor属性为它添加了一些子视图。我使用ios9 autolayout布置子视图,但即使视图在屏幕之外,UIScrollView仍然不会滚动。

import UIKit

class ViewController: UIViewController {

    let scrollView: UIScrollView = {
        let sv = UIScrollView()
        sv.translatesAutoresizingMaskIntoConstraints = false
        sv.backgroundColor = .gray
        return sv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(scrollView)

        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

        let view1 = UIView()
        view1.backgroundColor = .red

        let view2 = UIView()
        view2.backgroundColor = .blue

        let view3 = UIView()
        view3.backgroundColor = .green

        let view4 = UIView()
        view4.backgroundColor = .purple

        let views = [view1, view2, view3, view4]

        for view in views {
            scrollView.addSubview(view)
            view.translatesAutoresizingMaskIntoConstraints = false
        }

        view1.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        view1.leftAnchor.constraint(equalTo: scrollView.leftAnchor).isActive = true
        view1.heightAnchor.constraint(equalToConstant: 140).isActive = true
        view1.widthAnchor.constraint(equalToConstant: 140).isActive = true

        view2.topAnchor.constraint(equalTo: view1.bottomAnchor, constant: 100).isActive = true
        view2.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
        view2.heightAnchor.constraint(equalToConstant: 140).isActive = true
        view2.widthAnchor.constraint(equalToConstant: 140).isActive = true

        view3.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 50).isActive = true
        view3.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
        view3.heightAnchor.constraint(equalToConstant: 140).isActive = true
        view3.widthAnchor.constraint(equalToConstant: 140).isActive = true

        view4.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 20).isActive = true
        view4.leftAnchor.constraint(equalTo: view1.rightAnchor).isActive = true
        view4.heightAnchor.constraint(equalToConstant: 140).isActive = true
        view4.widthAnchor.constraint(equalToConstant: 140).isActive = true
    }

}

1 个答案:

答案 0 :(得分:0)

在UIScrollViews中使用Autolayout时,您必须将子视图固定在滚动视图的顶部和底部,以允许滚动视图计算其contentSize。

添加此行可修复它:

view4.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true