IOS中使用NSAttributedString靈活創(chuàng)建標(biāo)簽

字號(hào):


    靈活使用NSAttributedString可以更輕松的創(chuàng)建出內(nèi)容復(fù)雜的標(biāo)簽。需要注意一點(diǎn):如果一個(gè)label設(shè)置了這個(gè)屬性,那它其他的設(shè)置都將失效。
    首先,我們初始化一個(gè)NSMutableAttributedString對(duì)象。
    //通過(guò)字符串初始化
    //- (instancetype)initWithString:(NSString *)str;
    //通過(guò)字符串和屬性字典直接初始化
    //- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
    //通過(guò)自身對(duì)象初始化
    //- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;
    NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc]initWithString:@"123!@#你好么QWE"];
    可以通過(guò)下面兩個(gè)函數(shù)對(duì)attrebute字符串進(jìn)行設(shè)置與修改
    //可以替換字符
    - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;
    //屬性設(shè)置
    - (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
    //設(shè)置一定范圍內(nèi)字符屬性
    - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
    字典的鍵值對(duì)應(yīng)如下:
    //kCTFontAttributeName 這個(gè)鍵是字體的名稱 必須傳入CTFont對(duì)象
    //kCTKernAttributeName 這個(gè)鍵設(shè)置字體間距 傳入必須是數(shù)字對(duì)象 默認(rèn)為0
    //kCTLigatureAttributeName 這個(gè)鍵設(shè)置連字方式 必須傳入CFNumber對(duì)象
    //kCTParagraphStyleAttributeName 段落對(duì)其方式
    //kCTForegroundColorAttributeName 字體顏色 必須傳入CGColor對(duì)象
    //kCTStrokeWidthAttributeName 筆畫寬度 必須是CFNumber對(duì)象
    //kCTStrokeColorAttributeName 筆畫顏色
    //kCTSuperscriptAttributeName 控制垂直文本定位 CFNumber對(duì)象
    //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)];
    通過(guò)測(cè)試,發(fā)現(xiàn)上面有些鍵值并沒有作用,可以替換下面的方法,效果相同,不同的地方在于其傳值的類型不同,下面的方法更加方便(使用UIFont UIColor NSString 和一些系統(tǒng)枚舉)
    NSParagraphStyleAttributeName
    NSForegroundColorAttributeName
    NSBackgroundColorAttributeName
    NSLigatureAttributeName
    NSKernAttributeName
    NSStrikethroughStyleAttributeName
    NSUnderlineStyleAttributeName
    NSStrokeColorAttributeName
    NSStrokeWidthAttributeName
    NSShadowAttributeName
    NSTextEffectAttributeName
    NSAttachmentAttributeName
    NSLinkAttributeName
    NSBaselineOffsetAttributeName
    NSUnderlineColorAttributeName
    NSStrikethroughColorAttributeName
    NSObliquenessAttributeName
    NSExpansionAttributeName
    NSWritingDirectionAttributeName
    NSVerticalGlyphFormAttributeName