How to Set constraints for UILabels programmatically Where Label Count is equal to Main screen Height in Swift

Viewed 588

I would like to create this Format

label 1 | label 2 | label 3 | label 4
label 5| label 6| label 7|

where labels Count is equal to View Height. and want to set constraints also. The code below is the Create UILabels:

for i in 0...Int(self.view.frame.height)
{
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
    label.textAlignment = NSTextAlignment.center
    label.text = "label"
    label.sizeToFit()
    self.view.addSubview(label)
}
2 Answers

It looks you want to stack 4 labels in each row.

If you support iOS > 9.0, use UIStackView.

Otherwise, you have to calculate the spacing between the labels for each row:

let spacing = (screenWidth -  (w1 + w2 + w3+ w4))/5

And add the constraints programmatically with .addConstraints.

The better way to do it is by using Visual format language but I can't help you out with an answer with context to VFS because I personally don't use it.

But if you want to do it with NSLayoutConstraint then it can be done in a very easy way.

I am not writing the exact code but would explain to you how you have to deal this out.

Note - Don't forget to set translatesAutoresizingMaskIntoConstraints = false and Don't forget to set isActive = true on all the constraints which you want to keep active.

because if you forget to do it then your code won't work

Then align left label1 to the parent view you can either do this by anchors or NSLayoutConstraints I would recommend doing it with Anchor.

label1.leadingAnchor.constraint(equalTo: parentView.leadingAnchor, constant: 0).isActive = true

Then align other label's leading edge to the trailing edge of the previous one like -

label2.leadingAnchor.constraint(equalTo: label1.leadingAnchor, constant: 0).isActive = true

and finally, align the rightmost label to the trailing edge of parent view like -

rightMostLabel.trailingAnchor.constraint(equalTo: parentView.trailingAnchor, constant: 0).isActive = true

Then set the top alignment of the label1 with respect to the parent view

label1.topAnchor.constraint(equalTo: parentView.topAnchor, constant: 0).isActive = true

Then finally set the width of all the labels equal to any one of the label. Let's say, we set the width of all the labels equal to label1. by-

NSLayoutConstraint(item: label1, attribute: .width, relatedBy: .equal, toItem: label2, attribute: .width, multiplier: 1, constant: 0).isActive = true

This code above was with label1 and label2 you would have to do it again with label2 and label3 and so on.

Related