3

属性を NSAttributedString に適用できることはわかっています。

しかし、同じ属性文字列に異なる属性を適用するにはどうすればよいでしょうか。

文字列「これは属性付きのテキストです。」

特定の属性 (背景色または前景色) を「これは」別の属性 (背景色または前景色) を「属性付きテキスト」に設定するにはどうすればよいでしょうか。

これを達成する方法はありますか....?

また、iOS で NSAttributedString の背景色を設定する方法はありますか?

4

2 に答える 2

4

属性付き文字列の可変コピーを作成してから、次のいずれかを使用します。

-setAttributes:range:
-addAttributes:range:
-addAttribute:value:range:
-removeAttributes:range:

たとえば、最初の4文字に赤い色を設定するには:

NSMutableAttributedString *mutAttrStr = [attributedString mutableCopy];
CGColorRef redClr = [UIColor redColor].CGColor;
NSDictionary *newAttributes = [NSDictionary dictionaryWithObject:(id)redClr forKey:(id)kCTForegroundColorAttributeName];
[mutAttrStr addAttributes:newAttributes range:NSMakeRange(0, 4)];

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html

iOSで背景色を描画する組み込みの方法はありません。「MyBackgroundColorAttributeName」などの属性のカスタム文字列定数を作成してから、自分で描画する必要があります。

于 2011-12-16T06:36:06.243 に答える