mik.ro
mik.ro

Reputation: 4903

Resize uiscrollview after adding content programmatically

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?

Upvotes: 0

Views: 175

Answers (3)

Naser Mohamed
Naser Mohamed

Reputation: 146

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

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100541

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

Upvotes: 1

User18474728
User18474728

Reputation: 361

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

Upvotes: 0

Related Questions