iOS-NSAttributedString,nsattributedstring
一、NSAttributeString簡介
NSAttributedString叫做富文本,是一種帶有屬性的字串,通過它可以輕鬆的在一個字串中表現出多種字型、字型大小、字型大小等各不相同的風格,還可以對段落進行格式化。
二、字元屬性
1.NSString *const NSFontAttributeName(字型):
該屬性所對應的值是一個 UIFont 對象。該屬性用於改變一段文本的字型。如果不指定該屬性,則預設為12-point Helvetica(Neue)。
2.NSString *const NSParagraphStyleAttributeName(段落):
該屬性所對應的值是一個 NSParagraphStyle 對象。該屬性在一段文本上應用多個屬性。如果不指定該屬性,則預設為 NSParagraphStyle 的 defaultParagraphStyle 方法返回的預設段落屬性。想要瞭解NSParagraphStyle可以自行百度學習,在這裡不詳細描述。注意:lable的numberOfLines屬性必須設定為0,段落樣式才會生效。
3.NSString *const NSForegroundColorAttributeName(字型顏色):
該屬性所對應的值是一個 UIColor 對象。該屬性用於指定一段文本的字型顏色。如果不指定該屬性,則預設為黑色。
4.NSString *const NSBackgroundColorAttributeName(字型背景色):
該屬性所對應的值是一個 UIColor 對象。該屬性用於指定一段文本的背景顏色。如果不指定該屬性,則預設無背景色。
5.NSString *const NSLigatureAttributeName(連字號):
該屬性所對應的值是一個 NSNumber 對象(整數)。連體字元是指某些連在一起的字元,它們採用單個的圖元符號。0 表示沒有連體字元。1 表示使用預設的連體字元。2表示使用所有連體符號。預設值為 1(注意,iOS 不支援值為 2)。
6.NSString *const NSKernAttributeName(字間距):
該屬性所對應的值是一個 NSNumber 對象(整數)。連體字元是指某些連在一起的字元,它們採用單個的圖元符號。0 表示沒有連體字元。1 表示使用預設的連體字元。2表示使用所有連體符號。預設值為 1(注意,iOS 不支援值為 2)。
7.NSString *const NSStrikethroughStyleAttributeName(刪除線):
該屬性所對應的值是一個 NSNumber 對象(整數)。該值指定是否在文字上加上刪除線,該值參考“Underline Style Attributes”。預設值是NSUnderlineStyleNone。
8.NSString *const NSUnderlineStyleAttributeName(底線):
該屬性所對應的值是一個 NSNumber 對象(整數)。該值指定是否在文字上加上底線,該值參考“Underline Style Attributes”。預設值是NSUnderlineStyleNone。
9.NSString *const NSStrokeColorAttributeName(邊線顏色):
該屬性所對應的值是一個 UIColor 對象。如果該屬性不指定(預設),則等同於 NSForegroundColorAttributeName。否則,指定為刪除線或底線顏色。更多細節見“Drawing attributedstrings that are both filled and stroked”。
10.NSString *const NSStrokeWidthAttributeName(邊線寬度):
該屬性所對應的值是一個 NSNumber 對象(小數)。該值改變描邊寬度(相對於字型size 的百分比)。預設為 0,即不改變。正數只改變描邊寬度。負數同時改變文字的描邊和填充寬度。例如,對於常見的空心字,這個值通常為3.0。
11.NSString *const NSShadowAttributeName(陰影):
該屬性所對應的值是一個 NSShadow 對象。預設為 nil。
12.NSString *const NSVerticalGlyphFormAttributeName(橫豎排版):
該屬性所對應的值是一個 NSNumber 對象(整數)。0 表示橫排文本。1 表示豎排文本。在 iOS 中,總是使用橫排文本,0 以外的值都未定義。
三、程式碼範例
在這裡給大家舉了幾個簡單的例子,有興趣的可以嘗試其餘屬性的效果。
// 樣本Lable UILabel *exLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 40)]; exLabel.textAlignment = NSTextAlignmentCenter; [self.view addSubview:exLabel]; NSString *exString = @"查看人數:150人"; // 富文字物件 NSMutableAttributedString *exAttributedString = [[NSMutableAttributedString alloc] initWithString:exString]; // 富文本樣式 // 通過addAttribute方法設定樣式 // 參數分別是字元屬性,值,改變範圍 // 字型顏色 [exAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5, 4)]; // 字型大小 [exAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:25] range:NSMakeRange(5, 4)]; // 背景顏色 [exAttributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor grayColor] range:NSMakeRange(5, 4)]; // 字間距 [exAttributedString addAttribute:NSKernAttributeName value:[NSNumber numberWithInt:5] range:NSMakeRange(5, 4)]; exLabel.attributedText = exAttributedString;
: