How to Add Constraints Programmatically to My Uilabel

Creating UILabel programmatically with constraints?

Like you said, we already have x, y and height available for the label, i.e.

let x: CGFloat = 0
let y: CGFloat = 0
let height: CGFloat = 50

Let's create a label using the above details. Also set the width of the label as UIScreen.main.bounds.width as per your requirement.

let label = UILabel(frame: CGRect(x: x, y: y, width: UIScreen.main.bounds.width, height: height))
label.text = "This is a sample text"

Don't forget to set label's translatesAutoresizingMaskIntoConstraints as false and add it to whatever subview you want.

label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)

Add the relevant constraints of label with its superview - top, bottom, leading, height. You can definitely add bottom constraint if required. That totally depends upon your UI.

I'm adding the label to the top of the viewController's view.

NSLayoutConstraint.activate([
label.heightAnchor.constraint(equalToConstant: height),
view.topAnchor.constraint(equalTo: label.topAnchor),
view.leadingAnchor.constraint(equalTo: label.leadingAnchor),
view.trailingAnchor.constraint(equalTo: label.trailingAnchor)
])

Created UILabel programmatically with constraints. Now i want to update the height constraints of the UILabel

Create a var

var heightCon:NSLayoutConstraint!

Assign

heightCon = movieDescLbl.heightAnchor.constraint(equalToConstant: 87)
heightCon.isActive = true

Update

heightCon.constant = 200
view.layoutIfNeeded()

OR

heightCon.isActive = true/false

Programmatically change constraint on a UILabel breaks layout

I figured it out. What was happening was the UILabel's height was not constrained, so when the second constraint was deactivated and the first constraint reactivated the height automatically increased (see image below). To fix this I had to manually constrain the height of all of my view items. If anyone has a better solution please post it as I'd prefer not to manually set the height for each item because that might cause the layouts to break on different devices.

Sample Image

UPDATE

Thanks to siburb for pointing out the Content Hugging Priority property for UI Elements. The root of my issue was that this property was not being set which allowed for my UILabel's height to expand. The solution was to set this property to a value of 750 or higher.

[myLabel setContentHuggingPriority:750 forAxis:UILayoutConstraintAxisVertical];

How to set UILabel only width and height and constraints programmatically

To create label with height and width constraints here is the constraints...And don't forget to add label in to view with addSubview method

UILabel *Label = [[UILabel alloc] init];
[Label setTranslatesAutoresizingMaskIntoConstraints:NO];

[self.view addSubview:Label];

// Width constraint
[Label addConstraint:[NSLayoutConstraint constraintWithItem:Label
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier:1
constant:200]];

// Height constraint
[Label addConstraint:[NSLayoutConstraint constraintWithItem:Label
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier:1
constant:21]];

Swift 4:

label.translatesAutoresizingMaskIntoConstraints = false
label.addConstraint(NSLayoutConstraint(item: label, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 21))
label.addConstraint(NSLayoutConstraint(item: label, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200))

And In Swift

 Label.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(Label)

Label.addConstraint(NSLayoutConstraint(item: Label, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 21))
Label.addConstraint(NSLayoutConstraint(item: Label, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 200))

Check this link for more detail

UPDATE

As you update your question, here is my updated answer...

UILabel *Label1 = [[UILabel alloc] init];
[Label1 setTranslatesAutoresizingMaskIntoConstraints:NO];
UILabel *Label2 = [[UILabel alloc] init];
[Label2 setTranslatesAutoresizingMaskIntoConstraints:NO];

Label1.text = @"Label1";
Label1.backgroundColor = [UIColor blueColor];
Label2.text = @"Label2";
Label2.backgroundColor = [UIColor redColor];

[self.view addSubview:Label1];
[self.view addSubview:Label2];

// Width constraint
[Label1 addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier:1
constant:280]];

// Height constraint
[Label1 addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute: NSLayoutAttributeNotAnAttribute
multiplier:1
constant:21]];

// CenterX constraint
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.view
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:Label1
attribute: NSLayoutAttributeCenterX
multiplier:1
constant:0]];
// Top constraint
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:self.topLayoutGuide
attribute: NSLayoutAttributeBottom
multiplier:1
constant:40]];


// label2
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:Label2
attribute: NSLayoutAttributeLeading
multiplier:1
constant:0]];
// label2.Height = label1.Height
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:Label2
attribute: NSLayoutAttributeHeight
multiplier:1
constant:0]];
// label2.width = label1.width
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label1
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:Label2
attribute: NSLayoutAttributeWidth
multiplier:1
constant:0]];

// label2.Top
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:Label2
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:Label1
attribute: NSLayoutAttributeBottom
multiplier:1
constant:34]];

Result Screen

Sample Image

How to programmatically add constraints from label to UICollectionViewCell?

Assuming the label is a subview from the CollectionViewController, it can be done like:

label.topAnchor.constraint(equalTo: cell.bottomAnchor, constant: someConstant).isActive = true

The above code works for me at least with an UITableViewController and its cells, so it should also work with a UICollectionView.

Swift 3 Create UILabel programmatically and add NSLayoutConstraints

See below code as an example

let lblNew = UILabel()
lblNew.backgroundColor = UIColor.blue
lblNew.text = "Test"
lblNew.textColor = UIColor.white
lblNew.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(lblNew)

let widthConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 300)
let heightConstraint = NSLayoutConstraint(item: lblNew, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200)
var constraints = NSLayoutConstraint.constraints(
withVisualFormat: "V:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterX,
metrics: nil,
views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

// Center vertically
constraints = NSLayoutConstraint.constraints(
withVisualFormat: "H:[superview]-(<=1)-[label]",
options: NSLayoutFormatOptions.alignAllCenterY,
metrics: nil,
views: ["superview":view, "label":lblNew])

view.addConstraints(constraints)

view.addConstraints([ widthConstraint, heightConstraint])


Related Topics



Leave a reply



Submit