ios - Setting attributedstring to label with backgroundcolor


Keywords:ios 


Question: 

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


1 Answer: 

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.