IOS中使用NSAttributedString靈活創(chuàng)建標簽
來源:易賢網(wǎng) 閱讀:1417 次 日期:2015-05-08 14:30:55
溫馨提示:易賢網(wǎng)小編為您整理了“IOS中使用NSAttributedString靈活創(chuàng)建標簽”,方便廣大網(wǎng)友查閱!

靈活使用NSAttributedString可以更輕松的創(chuàng)建出內(nèi)容復雜的標簽。需要注意一點:如果一個label設置了這個屬性,那它其他的設置都將失效。

首先,我們初始化一個NSMutableAttributedString對象。

//通過字符串初始化

//- (instancetype)initWithString:(NSString *)str;

//通過字符串和屬性字典直接初始化

//- (instancetype)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;

//通過自身對象初始化

//- (instancetype)initWithAttributedString:(NSAttributedString *)attrStr;

NSMutableAttributedString * attribute = [[NSMutableAttributedString alloc]initWithString:@"123!@#你好么QWE"];

可以通過下面兩個函數(shù)對attrebute字符串進行設置與修改

//可以替換字符

- (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str;

//屬性設置

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

//設置一定范圍內(nèi)字符屬性

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

字典的鍵值對應如下:

//kCTFontAttributeName 這個鍵是字體的名稱 必須傳入CTFont對象

//kCTKernAttributeName 這個鍵設置字體間距 傳入必須是數(shù)字對象 默認為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)];

通過測試,發(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

更多信息請查看IT技術專欄

更多信息請查看技術文章
易賢網(wǎng)手機網(wǎng)站地址:IOS中使用NSAttributedString靈活創(chuàng)建標簽

2026國考·省考課程試聽報名

  • 報班類型
  • 姓名
  • 手機號
  • 驗證碼
關于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡要咨詢 | 簡要咨詢須知 | 新媒體/短視頻平臺 | 手機站點 | 投訴建議
工業(yè)和信息化部備案號:滇ICP備2023014141號-1 云南省教育廳備案號:云教ICP備0901021 滇公網(wǎng)安備53010202001879號 人力資源服務許可證:(云)人服證字(2023)第0102001523號
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關注公眾號:hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權所有:易賢網(wǎng)