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.
Transferred from http://my.oschina.net/CarlHuang/blog/138363;
Real code:
. h file
| 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
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 (GO)