靈活使用NSAttributedString能夠更輕鬆的建立出內容複雜的標籤。須要注意一點:若是一個label設置了這個屬性,那它其餘的設置都將失效。函數
首先,咱們初始化一個NSMutableAttributedString對象。測試
//經過字符串初始化 //- (instancetype)initWithString:(NSString *)str; //經過字符串和屬性字典直接初始化 //- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs; //經過自身對象初始化 //- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr; NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc]initWithString:@"123!@#你好麼QWE"];
能夠經過下面兩個函數對attrebute字符串進行設置與修改字體
//能夠替換字符 - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str; //屬性設置 - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range; //設置必定範圍內字符屬性 - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
字典的鍵值對應以下:code
//kCTFontAttributeName 這個鍵是字體的名稱 必須傳入CTFont對象 //kCTKernAttributeName 這個鍵設置字體間距 傳入必須是數字對象 默認爲0 //kCTLigatureAttributeName 這個鍵設置連字方式 必須傳入CFNumber對象 //kCTParagraphStyleAttributeName 段落對其方式 //kCTForegroundColorAttributeName 字體顏色 必須傳入CGColor對象 //kCTStrokeWidthAttributeName 筆畫寬度 必須是CFNumber對象 //kCTStrokeColorAttributeName 筆畫顏色 //kCTSuperscriptAttributeName 控制垂直文本定位 CFNumber對象 //kCTUnderlineColorAttributeName 下劃線顏色 [attribute addAttribute:(NSString*)kCTKernAttributeName value:@5 range:NSMakeRange(0, 5)]; [attribute addAttribute:(NSString *)kCTFontAttributeName value:(id)CFBridgingRelease(CTFontCreateWithName((CFStringRef)[UIFont boldSystemFontOfSize:14].fontName, 14, NULL)) range:NSMakeRange(0, 4)]; [attribute addAttribute:(NSString *)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleDouble] range:NSMakeRange(0, 4)];
經過測試,發現上面有些鍵值並無做用,能夠替換下面的方法,效果相同,不一樣的地方在於其傳值的類型不一樣,下面的方法更加方便(使用UIFont UIColor NSString 和一些系統枚舉)orm
NSParagraphStyleAttributeName NSForegroundColorAttributeName NSBackgroundColorAttributeName NSLigatureAttributeName NSKernAttributeName NSStrikethroughStyleAttributeName NSUnderlineStyleAttributeName NSStrokeColorAttributeName NSStrokeWidthAttributeName NSShadowAttributeName NSTextEffectAttributeName NSAttachmentAttributeName NSLinkAttributeName NSBaselineOffsetAttributeName NSUnderlineColorAttributeName NSStrikethroughColorAttributeName NSObliquenessAttributeName NSExpansionAttributeName NSWritingDirectionAttributeName NSVerticalGlyphFormAttributeName
專一技術,熱愛生活,交流技術,也作朋友。對象
——琿少 QQ羣:203317592ip