NSMutableAttributedString常見的屬性:字體
NSFontAttributeName 字體spa
NSForegroundColorAttributeName 文字顏色code
NSBackgroundColorAttributeName 背景顏色orm
NSStrikethroughStyleAttributeName 刪除線(默認是0,無刪除線)ci
NSUnderlineStyleAttributeName 下劃線(默認是0,無下劃線)it
NSParagraphStyleAttributeName 設置段落/間距io
使用方法:table
爲某一範圍內文字設置多個屬性class
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;方法
爲某一範圍內文字添加某個屬性
- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
爲某一範圍內文字添加多個屬性
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 300, 100)]; label.numberOfLines = 0; label.font = [UIFont systemFontOfSize:18]; NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:@"你說你最愛丁香花,由於你的名字就是它,多麼憂鬱的花,多愁善感的人啊!"]; //設置文字顏色以及字體、刪除線 NSDictionary * dict = @{ NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:13], NSStrikethroughStyleAttributeName:@"1"}; //從下標0開始,長度爲18的內容設置多個屬性,dict裏面寫的就是設置的屬性 [str setAttributes:dict range:NSMakeRange(0, 18)]; //設置背景顏色以及下劃線 NSDictionary * dict1 = @{ NSBackgroundColorAttributeName:[UIColor yellowColor], NSUnderlineStyleAttributeName:@"1"}; //從下標14開始,長度爲6的內容添加多個屬性,dict1裏面寫的就是添加的屬性 [str addAttributes:dict1 range:NSMakeRange(14, 6)]; //從下標21開始,長度爲2的內容添加字體屬性,設置其字號爲22 [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(21, 2)]; label.attributedText = str; [self.view addSubview:label];
UITextView *titleText = [[UITextView alloc] initWithFrame:CGRectMake(10, 200, 300, 300)]; titleText.text = @"說不上爲何,我變得很主動。若愛上一我的,什麼都會值得去作。我想大聲宣佈,對你戀戀不捨。連隔壁鄰居都猜到我如今的感覺,河邊的風在吹着頭髮飄動,牽着你的手一陣莫名感動。我想帶你回個人外婆家,一塊兒看着日落,一直到咱們都睡着。我想就這樣牽着你的手不放開,愛能不可以永遠單純沒有悲哀,我想帶你騎單車,我想和你看棒球,想這樣沒擔心唱着歌一直走!"; titleText.font = [UIFont systemFontOfSize:12]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = 10;//行間距 //設置字號和行間距 NSDictionary *ats = @{ NSFontAttributeName : [UIFont systemFontOfSize:16.0f], NSParagraphStyleAttributeName : paragraphStyle, }; titleText.attributedText = [[NSAttributedString alloc] initWithString:titleText.text attributes:ats];//設置行間距 [self.view addSubview:titleText];
若是是給Label設置的行間距,設置完之後,獲取label的高度方法:
//獲取設置文本間距之後的高度,210是控件的寬度,須要寫一致,否則獲取的高度有問題 CGRect fram = [dataLabel.attributedText boundingRectWithSize:CGSizeMake(210, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin context:nil]; NSLog(@"-----高度是%f",fram.size.height);