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):
let attributedString = NSMutableAttributedString()
attributedString.append(NSAttributedString(string: "test ",
attributes: [.underlineStyle: 0]))
attributedString.append(NSAttributedString(string: "s",
attributes: [.underlineStyle: NSUnderlineStyle.single.rawValue]))
attributedString.append(NSAttributedString(string: "tring",
attributes: [.underlineStyle: 0]))
Objective-C:
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 :(
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…