有的時候需要顯示的字符串帶有不同顏色翁巍,字體大小也不同,這時就可以用NSMutableAttributedString來設(shè)置字符串鸣皂。
通過設(shè)置Attributed(特性)來改變:
- NSForegroundColorAttributeName
- NSFontAttributeName
- NSStrokeColorAttributeName
- NSStrokeWidthAttributeName
- NSShadowAttributeName
- NSObliquenessAttributeName
- NSExpansionAttributeName
下面是主要代碼:
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"請到店出示您的編碼[5110001],為了您的賬戶安全請不要將您的編號隨意轉(zhuǎn)告他人,謝謝您的關(guān)顧"];
//設(shè)置文本顏色
[str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(1, 4)];
//設(shè)置文本字體大小
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 4)];
//設(shè)置文本顏色
[str addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(10,7)];
//設(shè)置文本字體大小
[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0] range:NSMakeRange(10, 7)];
//stroke
[str addAttribute:NSStrokeColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(5, 3)];
[str addAttribute:NSStrokeWidthAttributeName value:@(3.0) range:NSMakeRange(5, 3)];
[str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(5, 3)];
//加入陰影
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowColor = [UIColor redColor];
shadow.shadowOffset = CGSizeMake(0, 0);
shadow.shadowBlurRadius = 5.0;
[str addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(23, 4)];
//扭曲
[str addAttribute:NSObliquenessAttributeName value:@(1.0) range:NSMakeRange(27, 3)];
//擴(kuò)大
[str addAttribute:NSExpansionAttributeName value:@(0.5) range:NSMakeRange(30, 3)];
//設(shè)置段落間隔
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:10];
[str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
label1.attributedText = str;
label1.numberOfLines = 0;