web-dev-qa-db-ja.com

NSAttributedStringの部分文字列の属性を変更する

この質問は これ の重複である可能性があります。しかし、答えは私にはうまくいきません。もっと具体的にしたいと思います。

私はNSStringを持っていますが、NS(Mutable)AttributedStringが必要であり、この文字列のいくつかの単語には異なる色を指定する必要があります。私はこれを試しました:

NSString *text = @"This is the text and i want to replace something";

NSDictionary *attributes = @ {NSForegroundColorAttributeName : [UIColor redColor]};
NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] initWithString:@"AND" attributes:attributes];

NSMutableAttributedString *newText = [[NSMutableAttributedString alloc] initWithString:text];

newText = [[newText mutableString] stringByReplacingOccurrencesOfString:@"and" withString:[subString mutableString]];

「and」は大文字の赤である必要があります。

ドキュメントには、mutableStringが属性マッピングを保持することが記載されています。しかし、私が置き換えるものでは、割り当ての右側(コードスニペットの最終行)にattributedStringはもうありません。

どうすれば欲しいものを手に入れることができますか? ;)

17
mjay

@Hyperlordの回答は機能しますが、入力文字列に「and」という単語が1回だけ出現する場合に限られます。とにかく、私はNSStringのstringByReplacingOccurrencesOfString:最初にすべての「and」を「AND」に変更し、次に小さな正規表現を使用して属性付き文字列の一致を検出し、その範囲でNSForegroundColorAttributeNameを適用します。次に例を示します。

NSString *initial = @"This is the text and i want to replace something and stuff and stuff";
NSString *text = [initial stringByReplacingOccurrencesOfString:@"and" withString:@"AND"];

NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(AND)" options:kNilOptions error:nil];


NSRange range = NSMakeRange(0,text.length);

[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {

    NSRange subStringRange = [result rangeAtIndex:1];
    [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];

最後に、属性付きの文字列をラベルに適用します。

[myLabel setAttributedText:mutableAttributedString];
35
Mick MacCallum

既存のNSMutableAttributedStringを使用してNSStringを作成し、適切なNSRangeでスタイル属性を追加して、強調したい部分に色を付ける必要があると思います。次に例を示します。

NSString *text = @"This is the text and i want to replace something";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:text];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:[text rangeOfString:@"and"]];

注意:これは私の頭からのものであり、まったくテストされていません;-)

18
hyperlord

Swift 2でこのコードを試してください

var someStr = "This is the text and i want to replace something"
    someStr.replaceRange(someStr.rangeOfString("and")!, with: "AND")

    let attributeStr = NSMutableAttributedString(string: someStr)
    attributeStr.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: NSMakeRange(17, 3) )
    testLbl.attributedText = attributeStr
1
Masa S-AiYa

次に、属性付き文字列を使用してより複雑な操作(文字の追加/削除など)を行う場合に役立つ別の実装(Swift)を示します。

let text = "This is the text and i want to replace something"
let mutAttrStr = NSMutableAttributedString(string: text)

let pattern = "\\band\\b"
let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil)

while let result = regex!.firstMatchInString(mutAttrStr.string, options: .allZeros, range:NSMakeRange(0, count(mutAttrStr.string)) {
    let substring = NSMutableAttributedString(attributedString: mutAttrStr.attributedSubstringFromRange(result.range))

    // manipulate substring attributes here
    substring.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range NSMakeRange(0, count(substring.string))

    mutAttrStr.replaceCharactersInRange(result.range, withAttributedString: substring)
}

最終的な属性付き文字列は次のようになります。

let finalAttrStr = mutAttrStr.copy() as! NSAttributedString
0
ocwang