28

I want to create a UILabel programmatically with height, width and then I want to add constraints to it also programmatically for positioning the UILabel.

Update:

I want to create UI like this:

enter image description here

How to create this UI All programatically

Code to create one label label1 similarly I created two more label label2 and label3

UILabel *label1 = [[UILabel alloc]init];

label1.font = TitleFont;
label1.numberOfLines=0;
label1.text= @"Descriptions";
label1.lineBreakMode=NSLineBreakByWordWrapping;
[label1 sizeToFit];
label1.backgroundColor=[UIColor blueColor];
label1.textColor=[UIColor blackColor];
label1.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:label1];

And now I am able to add horizontal constraints them with this code

[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label1]-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(label1)]];

I am also able to set vertical constraint with view but I am unable to set constraint with from one label to another.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Varun Naharia
  • 5,318
  • 10
  • 50
  • 84

3 Answers3

84

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

enter image description here

A O
  • 5,516
  • 3
  • 33
  • 68
Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
  • can you please give me an example for creating two label one bottom to another with top constraint or bottom constraint to each other – Varun Naharia Jul 15 '15 at 13:10
  • please it's urgent I am I have to create a UI design all programmatically and I also want to add constraints to them because don't want to fix them on screen by giving x,y coordinates the Ui should look like one label on top and second bottom to it like wise i have to create more the two UIlabel – Varun Naharia Jul 15 '15 at 13:47
  • Actually I didn't find any good resource where I can learn all about adding constraints programatically that's why I asked you, Your knowledge is very high and I just want to know is there any single resource. By your example now I can make any UI completely programatically but now there is only one problem I am facing is now to know the missing constraints or extra constraints in the UI, Visually we can see that but by adding constraints programmatically how could we know this ? – Varun Naharia Jul 23 '15 at 04:31
  • 1
    you can check simple guide here....http://matthewmorey.com/creating-uiviews-programmatically-with-auto-layout/ – Bhavin Bhadani Jul 23 '15 at 04:41
  • Sorry for negative and un-constructive comment, but this is a pretty bad pile of code. I hope people will think before copying and pasting that. ...And no, i won't provide a better answer myself ;). I just felt like pointing that out. – user1244109 Oct 18 '16 at 20:04
2

i try this method to change height as text length in your label.

put viewdidload

[yourlabel setNumberOfLines:0];
    CGRect mainframe = _lbl_board.frame;
    mainframe.size.height =  [self getLabelHeight:yourlabel];
    yourlabel.frame = mainframe;

method

- (CGFloat)getLabelHeight:(UILabel*)label
{
    CGSize constraint = CGSizeMake(label.frame.size.width, CGFLOAT_MAX);
    CGSize size;

    NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
    CGSize boundingBox = [label.text boundingRectWithSize:constraint
                                                  options:NSStringDrawingUsesLineFragmentOrigin
                                               attributes:@{NSFontAttributeName:label.font}
                                                  context:context].size;

    size = CGSizeMake(ceil(boundingBox.width), ceil(boundingBox.height));

    return size.height;
}
Khushal iOS
  • 303
  • 2
  • 12
0

In Swift 3 : (just replace .Height by .height and .Equal by .equal)

self.addConstraint(NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 35))
Benoît
  • 13
  • 1
  • 7
  • better to use NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 35).active = true – Nosov Pavel Jun 23 '17 at 14:31