NSAttributedString
父類是NSObject
帶有屬性的字符串, 被稱為“富文本”
-
由2部分組成
- 文字內容 : NSString *
- 文字屬性 : NSDictionary *
NSAttributedString應用示例
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
attributes[NSForegroundColorAttributeName] = [UIColor yellowColor];
attributes[NSBackgroundColorAttributeName] = [UIColor redColor];
attributes[NSUnderlineStyleAttributeName] = @YES;
NSAttributedString *string = [[NSAttributedString alloc] initWithString:@"123" attributes:attributes];
NSAttributedString的字符屬性
- 字符屬性可以應用于 attributed string 的文本中。
1> NSFontAttributeName(字體)
NSString *const NSFontAttributeName;
該屬性所對應的值是一個 UIFont 對象。該屬性用于改變一段文本的字體。如果不指定該屬性,則默認為12-point Helvetica(Neue)。
2> NSParagraphStyleAttributeName(段落)
NSString *const NSParagraphStyleAttributeName;
該屬性所對應的值是一個 NSParagraphStyle 對象。該屬性在一段文本上應用多個屬性。如果不指定該屬性,則默認為 NSParagraphStyle 的defaultParagraphStyle 方法返回的默認段落屬性。
3> NSForegroundColorAttributeName(字體顏色)
NSString *const NSForegroundColorAttributeName;
該屬性所對應的值是一個 UIColor 對象。該屬性用于指定一段文本的字體顏色。如果不指定該屬性,則默認為黑色。
4> NSBackgroundColorAttributeName(字體背景色)
NSString *const NSBackgroundColorAttributeName;
該屬性所對應的值是一個 UIColor 對象。該屬性用于指定一段文本的背景顏色。如果不指定該屬性,則默認無背景色。
5> NSLigatureAttributeName(連字符)
NSString *const NSLigatureAttributeName;
該屬性所對應的值是一個 NSNumber 對象(整數)。連體字符是指某些連在一起的字符,它們采用單個的圖元符號。0 表示沒有連體字符。1 表示使用默認的連體字符。2表示使用所有連體符號。默認值為 1(注意,iOS 不支持值為 2)。
6> NSKernAttributeName(字間距)
NSString *const NSKernAttributeName;
該屬性所對應的值是一個 NSNumber 對象(整數)。字母緊排指定了用于調整字距的像素點數。字母緊排的效果依賴于字體。值為 0 表示不使用字母緊排。默認值為0。
7> NSStrikethroughStyleAttributeName(刪除線)
NSString *const NSStrikethroughStyleAttributeName;
該屬性所對應的值是一個 NSNumber 對象(整數)。該值指定是否在文字上加上刪除線,該值參考“Underline Style Attributes”。默認值是NSUnderlineStyleNone。
8> NSUnderlineStyleAttributeName(下劃線)
NSString *const NSUnderlineStyleAttributeName;
該屬性所對應的值是一個 NSNumber 對象(整數)。該值指定是否在文字上加上下劃線,該值參考“Underline Style Attributes”。默認值是NSUnderlineStyleNone。
9> NSStrokeColorAttributeName(邊線顏色)
NSString *const NSStrokeColorAttributeName;
該屬性所對應的值是一個 UIColor 對象。如果該屬性不指定(默認),則等同于 NSForegroundColorAttributeName。否則,指定為刪除線或下劃線顏色。更多細節見“Drawing attributedstrings that are both filled and stroked”。
10> NSStrokeWidthAttributeName(邊線寬度)
NSString *const NSStrokeWidthAttributeName;
該屬性所對應的值是一個 NSNumber 對象(小數)。該值改變描邊寬度(相對于字體size 的百分比)。默認為 0,即不改變。正數只改變描邊寬度。負數同時改變文字的描邊和填充寬度。例如,對于常見的空心字,這個值通常為3.0。
11> NSShadowAttributeName(陰影)
NSString *const NSShadowAttributeName;
該屬性所對應的值是一個 NSShadow 對象。默認為 nil。
12> NSVerticalGlyphFormAttributeName(橫豎排版)
NSString *const NSVerticalGlyphFormAttributeName;
該屬性所對應的值是一個 NSNumber 對象(整數)。0 表示橫排文本。1 表示豎排文本。在 iOS 中,總是使用橫排文本,0 以外的值都未定義。