iOS 8でNSMutableAttributedStringを使用して文字列の一部に下線を引くことができません 質問する

iOS 8でNSMutableAttributedStringを使用して文字列の一部に下線を引くことができません 質問する

文字列の一部に下線を引こうとします。たとえば、「' 一部 'テスト文字列' 文字列です。私は を使用しておりNSMutableAttributedString、私のソリューションは でうまく機能していましたiOS7

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

問題は、私のソリューションが で機能しなくなったことですiOS8。 の複数のバリエーションを 1 時間かけてテストした結果NSMutableAttributedString、このソリューションは範囲が 0 で始まる場合 (長さは異なる場合があります) にのみ機能することがわかりました。その理由は何でしょうか。どうすればこれを回避できますか。

ベストアンサー1

アップデート:この質問を調査すると、iOS 8 で NSMutableAttributedString を表示するついに解決策を見つけました!

文字列の先頭に NSUnderlineStyleNone を追加する必要があります。

Swift 4.2 (none削除されました):

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]))

目的:

 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"]];

このようなアプローチのもう 1 つの利点は、範囲が存在しないことです。ローカライズされた文字列に非常に適しています。

どうやらAppleのバグのようです:(

おすすめ記事