Reputation: 4903
I have an Contentview with uielements inside Uiscrollview. Below screenshot of my storyboard:
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).
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
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
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
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