Search code examples
swiftscrollview

Scrollview without NavigationController


I have no idea why I cannot add a working scroll view without embedding the VC in a navigation controller.

Here is my code for a VC which I open from a tab bar controller and it's not embedded in a navigation controller:

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
        }

I have a bunch of textfields and buttons in the stackview and they show up fine but the view does not scroll (vertically). What am I doing wrong?


Solution

  • You need to calculate the content size Ex.

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

    Also, try to consolidate your layout. Try using Autolayout