I try to underline part of a string, for example, a 'string' part in 'test string' string. I'm using NSMutableAttributedString
and my solution was working well on iOS7
.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
initWithString:@"test string"];
[attributedString addAttribute:NSUnderlineStyleAttributeName
value:@(NSUnderlineStyleSingle)
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 NSMutableAttributedString
, 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?
It worked for me
I used the following extension (using exidy's function) in playground/simulator and it worked fine , you may change/add attributes depending on your needs
It's September 2018, so this answer is not about iOS8 but it still relates to underlining part of a string.
Here is a Swift 4 extension that underlines a given term within an already composed
myAttributedString
Usage:
myAttributedString.underline(term: "some term")
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.
Swift 4.2 (
none
was removed):Objective-C:
Another bonus of such approach is absence of any ranges. Very nice for localized strings.
Seems like it is Apple bug :(
I found that if you apply UnderlineStyleNone to the whole string you can then selectively apply underline to a part that starts in the middle:
Add color for underline attribute: