首页 > 解决方案 > 如何在滚动视图中添加所有(标签、按钮、子视图)?

问题描述

我在主视图上设计了自动布局,但我忘记添加滚动视图。

我需要以编程方式添加滚动视图或重新设计我的视图吗?

这是我的代码

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)

标签: iosiphoneswiftxcode

解决方案


很难说你的视图控制器中有什么样的视图层次结构以及它们有什么样的关系,但这可能会以某种形式或形式帮助你。

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
    }
}

这是我在故事板上的视图控制器。视图控制器出现在屏幕上后,这两个视图将被包裹在滚动视图中。 在此处输入图像描述


推荐阅读