2

I have two labels next to each other, but the right one truncates even when I set truncate rules on the left one.

My code:

// Club name
labelFirst = [[UILabel alloc] init];
labelFirst.adjustsFontSizeToFitWidth = NO;
[labelFirst setLineBreakMode:NSLineBreakByTruncatingTail];
[labelFirst setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.contentView addSubview:labelFirst];

labelSecond = [[UILabel alloc] init];
[labelSecond setAdjustsFontSizeToFitWidth:NO];
[labelSecond setTranslatesAutoresizingMaskIntoConstraints:NO];
[labelSecond setText:NSLocalizedString(@"IsCancelled", nil)];
[self.contentView addSubview:labelSecond];

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-73-[label]-[label2]-10-|" options:0 metrics:nil views:@{@"label": labelFirst, @"label2": labelSecond}]
[self.contentView addConstraints:constraint];

How should I do this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Angelo A
  • 2,744
  • 6
  • 28
  • 37
  • 1
    Set the horizontal compression resistance priority of the right label to a higher value than the left one. – dan Dec 14 '15 at 14:39

2 Answers2

7

This is where Content Compression Resistance Priority comes into play. Set these values higher and lower based on which one you want compressed first. Higher for the label that you want take priority in resisting compression. Lower for the label that you want compressed (truncated) first.

You can do it programmatically (default is 750):

[labelFirst setContentCompressionResistancePriority:749
                                            forAxis:UILayoutConstraintAxisHorizontal];

Or in interface builder under the size inspector tab:

enter image description here

Here is another answer going into more detail on how they work.

j.f.
  • 3,908
  • 2
  • 29
  • 42
0

NSLineBreakByTruncatingTail - it's default LineBreakMode value for labels, change it for labelSecond to have diference

Igor
  • 1,537
  • 10
  • 12