In project development, we often encounter situations in which a uilabel uses different colors or different fonts to embody strings, and we can do this easily after iOS 6, and the official API gives us the attributedtext of the Uilabel class, Using strings of different colors and different fonts, we can use the Nsattributedtext and Nsmutableattributedtext classes to implement them.
Real code:
1234 |
@interface ViewController : UIViewController @property ( nonatomic , strong) IBOutlet UILabel *attrLabel; - ( IBAction )next:( id )sender; @end |
Add the following code to the. m file in the Viewdidload method:
123456789 |
self
.title = @
"For iOS 6 & later"
;
NSMutableAttributedString
*str = [[
NSMutableAttributedString
alloc] initWithString:@
"Using NSAttributed String"
];
[str addAttribute:
NSForegroundColorAttributeName
value:[UIColor blueColor] range:
NSMakeRange
(0,5)];
[str addAttribute:
NSForegroundColorAttributeName
value:[UIColor redColor] range:
NSMakeRange
(6,12)];
[str addAttribute:
NSForegroundColorAttributeName
value:[UIColor greenColor] range:
NSMakeRange
(19,6)];
[str addAttribute:
NSFontAttributeName
value:[UIFont fontWithName:@
"Arial-BoldItalicMT" size:30.0] range:
NSMakeRange
(0, 5)];
[str addAttribute:
NSFontAttributeName
value:[UIFont fontWithName:@
"HelveticaNeue-Bold"
size:30.0] range:
NSMakeRange
(6, 12)];
[str addAttribute:
NSFontAttributeName
value:[UIFont fontWithName:@
"Courier-BoldOblique" size:30.0] range:
NSMakeRange
(19, 6)];
attrLabel.attributedText = str;
|
IOS displays different fonts and colors in Uilabel (IOS6 and later)