在iOS開發中,經常會有一段文字顯示不一樣的顏色和字體,或者給某幾個文字加刪除線或下劃線的需求。以前在網上找了一些資料,有的是重繪UILabel的textLayer,有的是用html5實現的,都比較麻煩,並且不少UILabel的屬性也不起做用了,效果都不理想。後來瞭解到NSMuttableAttstring(帶屬性的字符串),上面的一些需求均可以很簡便的實現。html
實例化方法:html5
使用字符串初始化ios
- (id)initWithString:(NSString *)str;app
例:字體
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"今每天氣不錯呀"];ui
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;htm
字典中存放一些屬性名和屬性值,如:開發
NSDictionary *attributeDict = [NSDictionarydictionaryWithObjectsAndKeys:rem
[UIFontsystemFontOfSize:15.0],NSFontAttributeName,文檔
[UIColorredColor],NSForegroundColorAttributeName,
NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedStringalloc]initWithString:@"今每天氣不錯呀" attributes:attributeDict];
- (id)initWithAttributedString:(NSAttributedString *)attester;
使用NSAttributedString初始化,跟NSMutableString,NSString相似
使用方法:
爲某一範圍內文字設置多個屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
爲某一範圍內文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
爲某一範圍內文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
移除某範圍內的某個屬性
- (void)removeAttribute:(NSString *)name range:(NSRange)range;
NSFontAttributeName 字體
NSParagraphStyleAttributeName 段落格式
NSForegroundColorAttributeName 字體顏色
NSBackgroundColorAttributeName 背景顏色
NSStrikethroughStyleAttributeName 刪除線格式
NSUnderlineStyleAttributeName 下劃線格式
NSStrokeColorAttributeName 刪除線顏色
NSStrokeWidthAttributeName 刪除線寬度
NSShadowAttributeName 陰影
更多方法和屬性說明詳見蘋果官方說明文檔:
UILabel *testLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 320, 30)];
testLabel.backgroundColor = [UIColor lightGrayColor];
testLabel.textAlignment = NSTextAlignmentCenter;
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"今每天氣不錯呀"];
[AttributedStr addAttribute:NSFontAttributeName
value:[UIFont systemFontOfSize:16.0]
range:NSMakeRange(2, 2)];
[AttributedStr addAttribute:NSForegroundColorAttributeName
value:[UIColor redColor]
range:NSMakeRange(2, 2)];
testLabel.attributedText = AttributedStr;
[self.view addSubview:testLabel];
運行效果:
另外,其餘能夠設置text 的控件(如UIButton,UITextField)也都有該屬性,該文章不夠詳細,只是簡單介紹,其餘效果的實現參考API中更多的屬性及使用方法。