Chris
Chris

Reputation: 2274

ScrollView scrolls out of constraints

I have a UIScrollView and a UIStackView inside of it. My problem is that when scrolling, the content is scrolling out of its constraints. Why is that happening? Do I have to set some other constraints?

enter image description hereenter image description here

These are my constraints:

view.addSubview(theScrollView)
theScrollView.addSubview(theStackView)

    theScrollView.topAnchor.constraint(equalTo: theLabel.bottomAnchor, constant: 20).isActive = true
    theScrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30).isActive = true
    theScrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30).isActive = true
    theScrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    theStackView.topAnchor.constraint(equalTo: theScrollView.topAnchor).isActive = true
    theStackView.leadingAnchor.constraint(equalTo: theScrollView.leadingAnchor).isActive = true
    theStackView.trailingAnchor.constraint(equalTo: theScrollView.trailingAnchor).isActive = true
    theStackView.bottomAnchor.constraint(equalTo: theScrollView.bottomAnchor).isActive = true
    theStackView.widthAnchor.constraint(equalTo: theScrollView.widthAnchor).isActive = true

theLabel is the "Konto erstellen" at the top. Any idea how I can fit it ?

If there is anything unclear just let me know.

Upvotes: 0

Views: 59

Answers (1)

DonMag
DonMag

Reputation: 77462

In your SignUpViewController class...

  • you add theScrollView to view
  • you add theStackView to theScrollView
  • you add views to theStackView
    • theStackView.addArrangedSubview(emailView)
    • theStackView.addArrangedSubview(anzeigeNameView)
    • theStackView.addArrangedSubview(usernameView)
    • usw.

But you then add other views to view:

  • view.addSubview(emailTextField)
  • view.addSubview(anzeigeNameTextField)
  • view.addSubview(usernameTextField)

You then constrain those views to the views that are in theStackView. When you scroll the content, those view move with the stack view's subviews, but they are outside the hierarchy of the scroll view.

Instead, you need to do this:

    view.addSubview(theScrollView)
    theScrollView.addSubview(theStackView)

    theStackView.addArrangedSubview(emailView)
    emailView.addSubview(emailTextField)
    //view.addSubview(emailTextField)

    theStackView.addArrangedSubview(anzeigeNameView)
    anzeigeNameView.addSubview(anzeigeNameTextField)
    //view.addSubview(anzeigeNameTextField)

    theStackView.addArrangedSubview(usernameView)
    usernameView.addSubview(usernameTextField)
    //view.addSubview(usernameTextField)

Now your text fields will be subviews of their respective views, which are arranged subviews of the stack view.

You may need to adjust your constraints after doing this.

Upvotes: 1

Related Questions