0

I have two lined Label and setting the backgroundColor with an attributedString.

NSString *string = @"This is a UILAbel with two lines";

NSMutableAttributedString *mutableString = [[NSMutableAttributedString alloc]initWithString:
                                            string];

[mutableString setAttributes:@{NSBackgroundColorAttributeName : [UIColor redColor]} range:NSMakeRange(0, string.length)];

If the text makes a line break it fills the backgroundColor to the right border and in the second line it stops at the last character.

But I want the backgroundcolor in the first line just set to the last character too.

Pic example

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Klinki
  • 368
  • 1
  • 11

1 Answers1

0

The backgroundColor property is applied to the entire rect representing the label.

To resolve this you need to dynamically adjust your UILabel's frame depending on its content, in order to achieve the desired effect.

There is a method on UILabel called sizeToFit; try calling it.

Although I recommend you use autolayout and let the label resize itself based on constraints.

Woodstock
  • 22,184
  • 15
  • 80
  • 118