NSMutableAttributedString常見的屬性:
NSFontAttributeName 字體
NSForegroundColorAttributeName 文字顏色
NSBackgroundColorAttributeName 背景顏色
NSStrikethroughStyleAttributeName 刪除線(默認(rèn)是0,無刪除線)
NSUnderlineStyleAttributeName 下劃線(默認(rèn)是0检碗,無下劃線)
NSParagraphStyleAttributeName 設(shè)置段落/間距
使用方法:
為某一范圍內(nèi)文字設(shè)置多個(gè)屬性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
為某一范圍內(nèi)文字添加某個(gè)屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
為某一范圍內(nèi)文字添加多個(gè)屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
復(fù)制代碼
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 100)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:18];
NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:@"你說你最愛丁香花,因?yàn)槟愕拿志褪撬凼浚嗝磻n郁的花,多愁善感的人绑菁摇洼裤!"];
//設(shè)置文字顏色以及字體、刪除線
NSDictionary * dict = @{
NSForegroundColorAttributeName:[UIColor redColor],
NSFontAttributeName:[UIFont systemFontOfSize:13],
NSStrikethroughStyleAttributeName:@"1"};
//從下標(biāo)0開始,長度為18的內(nèi)容設(shè)置多個(gè)屬性腮鞍,dict里面寫的就是設(shè)置的屬性
[str setAttributes:dict range:NSMakeRange(0, 18)];
//設(shè)置背景顏色以及下劃線
NSDictionary * dict1 = @{
NSBackgroundColorAttributeName:[UIColor yellowColor],
NSUnderlineStyleAttributeName:@"1"};
//從下標(biāo)14開始值骇,長度為6的內(nèi)容添加多個(gè)屬性,dict1里面寫的就是添加的屬性
[str addAttributes:dict1 range:NSMakeRange(14, 6)];
//從下標(biāo)21開始移国,長度為2的內(nèi)容添加字體屬性吱瘩,設(shè)置其字號(hào)為22
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(21, 2)];
label.attributedText = str;
[self.view addSubview:label];
復(fù)制代碼
復(fù)制代碼
UITextView *titleText = [[UITextView alloc] initWithFrame:CGRectMake(10, 200, 300, 300)];
titleText.text = @"說不上為什么,我變得很主動(dòng)迹缀。若愛上一個(gè)人使碾,什么都會(huì)值得去做。我想大聲宣布祝懂,對(duì)你依依不舍票摇。連隔壁鄰居都猜到我現(xiàn)在的感受,河邊的風(fēng)在吹著頭發(fā)飄動(dòng)砚蓬,牽著你的手一陣莫名感動(dòng)矢门。我想帶你回我的外婆家,一起看著日落灰蛙,一直到我們都睡著祟剔。我想就這樣牽著你的手不放開,愛能不能夠永遠(yuǎn)單純沒有悲哀摩梧,我想帶你騎單車物延,我想和你看棒球,想這樣沒擔(dān)憂唱著歌一直走仅父!";
titleText.font = [UIFont systemFontOfSize:12];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = 10;//行間距
//設(shè)置字號(hào)和行間距
NSDictionary *ats = @{
NSFontAttributeName : [UIFont systemFontOfSize:16.0f],
NSParagraphStyleAttributeName : paragraphStyle,
};
titleText.attributedText = [[NSAttributedString alloc] initWithString:titleText.text attributes:ats];//設(shè)置行間距
[self.view addSubview:titleText];
復(fù)制代碼
如果是給Label設(shè)置的行間距叛薯,設(shè)置完以后,獲取label的高度方法:
//獲取設(shè)置文本間距以后的高度驾霜,210是控件的寬度案训,需要寫一致,不然獲取的高度有問題
CGRect fram = [dataLabel.attributedText boundingRectWithSize:CGSizeMake(210, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
NSLog(@"-----高度是%f",fram.size.height);