Search code examples
iosswiftscrollviewstackview

Swift : Is it possible to add an empty stackview inside a scrollview?


I have a fullscreen scrollview and inside a stackview that will be filled with elements at runtime. The problem is that I can't fix the missing constraints for the scrollview : Need constraints for Y position or height


Solution

  • The idea of the scrollView, is that it has "infinite" content size, so at the moment you are trying to add constraints inside it, he can't calculate them, my suggestion would be to add the stackView also programmatically as you do with the elements you might want to use this function to anchor the stackView to its superview(scrollView)

    func anchorSubview(_ view: UIView) {
        view.topAnchor.constraint(equalTo: self.topLayoutGuide.topAnchor).isActive = true
        view.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor).isActive = true
        view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
        view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
    }
    

    This should be done after you scrollView.addSubview(stackView)