NSAttributedString用法簡介,控制文字顏色,背景色等屬性
阿新 • • 發佈:2019-02-15
NSAttributedString用來管理字串以及和字串相關的屬性。
下面的程式碼是根據字元範圍設定label的text的顏色。
UIFont *font = [UIFont systemFontOfSize:14.0]; //行間距和字型 NSDictionary *dict1 = @{NSFontAttributeName:font}; //文字顏色 NSDictionary *dict2 = @{NSForegroundColorAttributeName:[UIColor greenColor]}; NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:@"attrStringString" attributes:dict1]; [attrString setAttributes:dict2 range:NSMakeRange(0, 6)]; UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 300)]; label.numberOfLines = 0; label.attributedText = attrString; [self.view addSubview:label];
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
方法中attrs字典中的部分屬性說明,詳細的請搜尋文件。
NSString *const NSFontAttributeName; 字型,value為UIFont型別NSString *const NSForegroundColorAttributeName; 文字顏色,value為UIColor型別
NSString *const NSBackgroundColorAttributeName; 文字背景色,value為UIColor型別
NSString *const NSKernAttributeName; 文字間距,value為NSNumber型別
NSString *const NSStrokeColorAttributeName; 鏤空效果顏色,value為UIColor型別
NSString *const NSStrokeWidthAttributeName; 鏤空效果字型邊框寬度,value為NSNumber型別