-
NSMutableAttributedString常見的屬性:
-
NSFontAttributeName 字體
-
NSForegroundColorAttributeName 文字顏色
-
NSBackgroundColorAttributeName 背景顏色
-
NSStrikethroughStyleAttributeName 刪除線(默認是0,無刪除線)
-
NSUnderlineStyleAttributeName 下划線(默認是0,無下划線)
-
NSParagraphStyleAttributeName 設置段落/間距
-
使用方法:
-
為某一范圍內文字設置多個屬性
-
- (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);
原博客地址:http://my.oschina.net/linxiaoxi1993/blog/469561