如何在带有约束的滚动视图中添加所有子视图

时间:2018-08-03 07:35:02

标签: ios iphone swift xcode

我设计了带有自动布局的视图,但是我忘记添加scrollView。

我想添加滚动视图而不使用情节提要和所有具有约束的子视图

这是我的代码

var scrollView: UIScrollView!

//viewDid load        
    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))

    for view in view.subviews{

        let constraint = 

        scrollView.addSubview(view)
    }
    scrollView.contentSize = CGSize(width: screenWidth, height: screenHeight)

1 个答案:

答案 0 :(得分:0)

很难说您在视图控制器中具有哪种视图层次结构以及它们之间的关系如何,但这可能会以某种形式或形状为您提供帮助。

class ViewController: UIViewController {
    lazy var scrollView: UIScrollView = {
        let s = UIScrollView()
        s.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(s)
        s.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        s.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        s.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        s.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        return s
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        let subviews = view.subviews

        // remove all subviews from main view
        view.subviews.forEach {
            $0.removeFromSuperview()
        }

        // create vertical stackview, this will help to write less constraints on each subview
        let stackView = UIStackView()
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.alignment = .fill
        stackView.axis = .vertical
        stackView.distribution = .fill

        // all all subviews in stackview
        subviews.forEach {
            stackView.addArrangedSubview($0)
        }

        // add stackview in main view
        scrollView.addSubview(stackView)
        stackView.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
        stackView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
        stackView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
        stackView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
        stackView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
    }
}

这是我在情节提要上的视图控制器。在视图控制器出现在屏幕上之后,这两个视图将被包装在scrollview中。 enter image description here