Reputation: 5498
I need some recommendation on how to add constraints to dynamically added UILabels
Say I have a UIView called (A) of size (screenwidth, 200) added to a UIViewcontroller view. On view A, I have set the autoresize masks on it's leading edge and trailing edge with the superview.
Now at runtime, I am adding UILabels with characters from a String. For example, if the string is "HELLO", I am adding five UILabels at equally spaced intervals for each character in HELLO.
When the orientation changes from portrait to landscape the UILabels are not evenly spaced. I haven't set any constraints on the UILabels and need some suggestion on how to add the constraints.
Is there any other solution other than constraints available to make the UILabels evenly spread out in landscape and portrait mode?
Thanks
Upvotes: 0
Views: 70
Reputation: 9925
I can recommend using UIStackView
s. Sweeper's solution is not using dynamic addition to the screen, so I thought I would provide a programmatic solution.
To add these dynamically, use the following example.
First:
@IBOutlet weak var containerView: UIView!
This should be view A from your description, and make sure to hook this up with the storyboard.
To add labels, we first add a stack view to the container view:
let stackView = UIStackView()
stackView.distribution = .fillEqually
stackView.alignment = .fill
stackView.spacing = 15
stackView.autoresizingMask = [.flexibleLeftMargin,.flexibleRightMargin]
containerView.addSubview(stackView)
stackView.centerXAnchor.constraint(equalTo: (stackView.superview?.centerXAnchor)!, constant: 0).isActive = true
stackView.centerYAnchor.constraint(equalTo: (stackView.superview?.centerYAnchor)!, constant: 0).isActive = true
stackView.heightAnchor.constraint(equalTo: (stackView.superview?.heightAnchor)!, constant: 0).isActive = true
stackView.widthAnchor.constraint(equalToConstant: 200).isActive = true
You can play around with the width anchor to get what you want.
Then when you want to add a label, use this:
let label = UILabel(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
label.text = "E"
stackView.addArrangedSubview(label)
let labelTwo = UILabel(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
labelTwo.text = "L"
stackView.addArrangedSubview(labelTwo)
//... And so on
Stack views make it easy to add subviews without too many constraints. However, you do have to add constraints to the stack view itself to get something on the screen!
I hope this helps.
Upvotes: 1
Reputation: 271410
In iOS 9, UIStackView
s got introduced. This is a great opportunity to use them!
The stack view will have constraints on leading, trailing and other necessary properties so that it stays where you want. The distribution of the stack view should be "Fill Equally".
Add an outlet to your VC and when needed, add your labels into the stack view!
Upvotes: 0