很久之前在簡書上看見過一篇類似的文章倚评,收藏過丘逸,但是時間久了单鹿,找不到了,于是自己記一下深纲,避免要用的時候又找不到了仲锄。
一般都是這么寫的
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 50, 300, 0)];
label.backgroundColor = [UIColor clearColor];
label.numberOfLines = 0;
NSMutableAttributedString* text =[[NSMutableAttributedString alloc]initWithString:string];
NSMutableParagraphStyle * paragraphStyle =[[NSMutableParagraphStyle alloc]init];
//設(shè)置行距
[paragraphStyle setLineSpacing:15.0f];
[text addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, string.length)];
//設(shè)置一定Range區(qū)間文字顏色
[text addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(0, 30)];
//設(shè)置一定Range區(qū)間文字下劃線
[text addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:NSMakeRange(0, 30)];
label.attributedText = text;
[self.view addSubview:label];
[label sizeToFit];
簡單寫法
[label setValue:@17 forKey:@"lineSpacing"];
注意使用的是KVC方式,其key為lineSpacing湃鹊,目前在iOS 14中使用還有效儒喊。