IOS displays different fonts and colors in Uilabel (GO)

Source: Internet
Author: User

Transferred from: http://my.oschina.net/CarlHuang/blog/138363

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 @interfaceViewController : UIViewController@property (nonatomic, strong) IBOutletUILabel *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 = [[NSMutableAttributedStringalloc] initWithString:@"Using NSAttributed String"];[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor blueColor] range:NSMakeRange(0,5)];[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor redColor] range:NSMakeRange(6,12)];[str addAttribute:NSForegroundColorAttributeNamevalue:[UIColor greenColor] range:NSMakeRange(19,6)];[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"Arial-BoldItalicMT" size:30.0] range:NSMakeRange(0, 5)];[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"HelveticaNeue-Bold"size:30.0] range:NSMakeRange(6, 12)];[str addAttribute:NSFontAttributeNamevalue:[UIFont fontWithName:@"Courier-BoldOblique" size:30.0] range:NSMakeRange(19, 6)];attrLabel.attributedText = str;

If you want to achieve this effect in previous versions of iOS6.0, you need to use a third-party library Tttattributedlabel, along with the import Coretext.frame framework.

IOS displays different fonts and colors in Uilabel (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.