0

I have an Contentview with uielements inside Uiscrollview. Below screenshot of my storyboard: enter image description here

I want to add the option for the app that if the user clicks the button it will add label on the bottom of the contentview (below red underscored label - dzialTerminOutlet). enter image description here

I'm adding the new label programmatically using following code:

let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false

label.backgroundColor = UIColor.orange
label.textColor = UIColor.black
label.textAlignment = NSTextAlignment.center
label.text = "test label"
contentView.addSubview(label)


label.topAnchor.constraint(equalTo: dzialTerminOutlet.bottomAnchor, constant: 10).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0)
label.widthAnchor.constraint(equalToConstant: 200.0)
label.heightAnchor.constraint(equalToConstant: 10.0)

The scrollview does not resize though. What's the issue here?

3 Answers 3

1

1- You need to activate

NSLayoutConstraint.activate([
  label.topAnchor.constraint(equalTo: dzialTerminOutlet.bottomAnchor, constant: 10),
  label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0),
  label.widthAnchor.constraint(equalToConstant: 200.0),
  label.heightAnchor.constraint(equalToConstant: 10.0)
])

2- You need to remove the bottom constraint established in IB between dzialTerminOutlet and contentView to be able to insert the new one and make the scrollView resize accordingly to avoid conflicts between it and

label.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 85.0)

so hook it as an outlet and deactivate it or search contentView for the bottom constraint and remove it

Sign up to request clarification or add additional context in comments.

2 Comments

Your answer seems very logic to me. However after i disable the bottom contraint (dzialTerminBottomConstraint.isActive = false) the scrollview gets shorter by 85 px.
make it -85 (minus)
0

Did you set scrollView contentSize with new size? scrollView.contentSize = CGSize(width: self.contentView.frame.size.width, height: self.contentView.frame.size.height)

Comments

0

a very simple way i'm using it a lot is to connect your contentView height constraint with an IBOutlet object and update it's value.

@IBOutlet weak var contentViewHeight : NSLayoutConstraint!

And after adding your label:

contentViewHeight.constant += labelHeight

Don't forget to set the contentView constraint (top, bottom, leading, trailing) = 0 with scroll view

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.