NSAttributedString、テキスト フォントの設定、前景色と背景色、取り消し線と影などを使用できます。
属性付き文字列は、文字とその属性を関連付けます。NSString オブジェクトと同様に、NSAttributedString と NSMutableAttributedString の 2 つのバリエーションがあります。以前のバージョンの iOS は属性付き文字列をサポートしていましたが、ボタン、ラベル、テキストフィールド、テキストビューなどのコントロールが属性を管理するプロパティを定義したのは、iOS 6 まででした。属性は文字の範囲に適用されるため、たとえば、文字列の一部だけに取り消し線属性を設定できます。また、属性付き文字列オブジェクトのデフォルト フォントが Helvetica 12 ポイントであることにも注意してください。完全な文字列以外の範囲にフォント属性を設定する場合は、このことに注意してください。次の属性は属性付き文字列で設定できます: NSString *const NSFontAttributeName; NSString *const NSParagraphStyleAttributeName; NSString *const NSForegroundColorAttributeName; NSString *const NSBackgroundColorAttributeName; NSString *const NSLigatureAttributeName; NSString *const NSKernAttributeName; NSString *const NSStrikethroughStyleAttributeName; NSString *const NSUnderlineStyleAttributeName; NSString *const NSStrokeColorAttributeName; NSString *const NSStrokeWidthAttributeName; NSString *const NSShadowAttributeName; NSString *const NSVerticalGlyphFormAttributeName;
下記は用例です
//-----------------------------
// Create attributed string
//-----------------------------
NSString *str = @"example for underline \nexample for font \nexample for bold \nexample for italics";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
// Add attribute NSUnderlineStyleAttributeName
//[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(12, 9)];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:NSUnderlineStyleSingle] range:NSMakeRange(12, 9)];
// Set background color for entire range
[attributedString addAttribute:NSBackgroundColorAttributeName
value:[UIColor yellowColor]
range:NSMakeRange(0, [attributedString length])];
// Create NSMutableParagraphStyle object
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentCenter;
// Add attribute NSParagraphStyleAttributeName
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraph range:NSMakeRange(0, [attributedString length])];
// Set font, notice the range is for the whole string
UIFont *font = [UIFont fontWithName:@"Helvetica" size:18];
[attributedString addAttribute:NSFontAttributeName value:font range:NSMakeRange(35, 4)];
// Set font, notice the range is for the whole string
UIFont *fontBold = [UIFont fontWithName:@"Helvetica-Bold" size:18];
[attributedString addAttribute:NSFontAttributeName value:fontBold range:NSMakeRange(53, 4)];
// Set font, notice the range is for the whole string
UIFont *fontItalics = [UIFont fontWithName:@"Helvetica-Oblique" size:18];
[attributedString addAttribute:NSFontAttributeName value:fontItalics range:NSMakeRange(71, 7)];
// Set label text to attributed string
[self.mytextView setAttributedText:attributedString];
`