Alessio Crestani
Alessio Crestani

Reputation: 1612

How to align and move two labels programmatically?

I have to use two sequential label, like:

Title: New Title

But title is a localized string that change his length in different languages. How to programmatically move the UILabel of New title at the end of Title ? With autoLayout the old solutions found on StackOverflow don't seem to be working.

Upvotes: 0

Views: 455

Answers (5)

NeverHopeless
NeverHopeless

Reputation: 11233

Try this as well:

[label1 setText:@"I am label1"];
[label2 setText:@"I am label2"];

CGRect frame = label1.frame;

[label2 setFrame:CGRectOffset(frame, frame.size.width, 0)];

Upvotes: 0

meaholik
meaholik

Reputation: 440

try to add NSLayoutConstraints between the leading of label2 and trailing of label1 with the constant

value = 0;

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:label2
                                                  attribute:NSLayoutAttributeLeading
                                                  relatedBy:NSLayoutRelationEqual
                                                     toItem:label1
                                                  attribute:NSLayoutAttributeTrailing
                                                 multiplier:1
                                                   constant:0]];

Upvotes: 0

Yogendra
Yogendra

Reputation: 1716

Use one string

  NSString *str = [NSString stringWithFormat:@"Title:%@   Newtitle:%@", Title, newtitle];

If color of title and text are different use attributed string like this example -

   NSMutableAttributedString *str = [[NSMutableAttributedString alloc]  initWithString:@"Its an test attributed string."];
    [str addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor]       range:NSMakeRange(3,5)];
[str addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor]      range:NSMakeRange(10,7)];
  [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:20.0] range:NSMakeRange(20, 10)];

Upvotes: 1

meaholik
meaholik

Reputation: 440

Why don't you use just one label with text is formated:

mylabel.text = [NSString stringWithFormat:@"%@: %@", Title, newtitle];

Upvotes: 0

pqteru
pqteru

Reputation: 451

set the second label frame after the first frame. label2 x point will be label1 x point + lable1 length.

Upvotes: 0

Related Questions