没有 NavigationController 的滚动视图

Scrollview without NavigationController

我不知道为什么不在导航控制器中嵌入 VC 就无法添加工作滚动视图。

这是我从标签栏控制器打开的 VC 的代码,它没有嵌入导航控制器中:

lazy var contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)

    lazy var scrollView : UIScrollView = {
        let scrollView = UIScrollView(frame: view.bounds)
        scrollView.backgroundColor = .white
        scrollView.frame = self.view.bounds
        scrollView.contentSize = contentSize
        scrollView.autoresizingMask = UIView.AutoresizingMask.flexibleHeight
        scrollView.bounces = true
        return scrollView
    }()

    lazy var containerView : UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.frame.size = contentSize
        return view
    }()

override func viewDidLoad() {
        super.viewDidLoad()

        setupElements()
    }

func setupElements() {

        view.backgroundColor = .white
        view.addSubview(scrollView)
        scrollView.addSubview(containerView)

        let stackView = UIStackView()
        containerView.addSubview(stackView)
        stackView.axis = .vertical
        stackView.distribution = .fillEqually
        stackView.spacing = 12

        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.topAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.topAnchor, constant: 60).isActive = true
        stackView.leadingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.leadingAnchor, constant: 20).isActive = true
        stackView.trailingAnchor.constraint(equalTo: containerView.safeAreaLayoutGuide.trailingAnchor, constant: -20).isActive = true
        }

我在 stackview 中有一堆文本字段和按钮,它们显示正常,但视图不滚动(垂直)。我做错了什么?

您的 scrollView 内容大小应大于您的 scrollView frame 以使其滚动

scrollView.contentSize = contentSize

您需要计算内容大小 例如

scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height + 100)

此外,请尝试巩固您的布局。尝试使用自动布局