KlimczakM KlimczakM - 1 year ago 228
iOS Question

Underline part of a string using NSMutableAttributedString in iOS8 is not working

I want to underline part of a string, for example 'string' part in 'test string' string. I'm using

and my solution was working well on iOS7.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
initWithString:@"test string"];
[attributedString addAttribute:NSUnderlineStyleAttributeName
range:NSMakeRange(5, 6)];
myLabel.attributedText = attributedString;

The problem is that my solution is not working in iOS8 anymore. After spending an hour on testing multiple variants of
I found out, that this solution works only when range starts with 0 (length can differ). What is the reason for that? How can I workaround this?

Answer Source

Update: By investigating this question: Displaying NSMutableAttributedString on iOS 8 I finally found the solution!

You should add NSUnderlineStyleNone at the beginning of the string.

 NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
 [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"test "
                                                                          attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleNone)}]];
 [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"s"
                                                                         attributes:@{NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle),
                                                                                      NSBackgroundColorAttributeName: [UIColor clearColor]}]];
 [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@"tring"]];

Another bonus of such approach is absence of any ranges. Very nice for localized strings.

Seems like it is Apple bug :(

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download