How to modify the Uilabel default font in IOS app development _ios

Source: Internet
Author: User
Tags uikit

On the basis of the project more mature, encountered such a demand, the application needs to introduce a new font, need to replace all the label's default font, but at the same time, for some special settings of the font label does not need to be replaced. At first glance, the problem is really tricky, the project is relatively large, a set of all the use of the label font workload is huge, and in many dynamic display of the interface, may be missing some label, creating bugs. Second, the label source in the project is not unique, useful code created, there are xib and storyboard, this will also waste a lot of energy. In this case, we may have the following two ways of handling.

I. Common methods
in a uilabel using a different color or a different font to reflect the string, after iOS 6 we can easily achieve this, the official API provides us with the Uilabel class of attributedtext, using different colors and different font strings, We can use the Nsattributedtext and Nsmutableattributedtext classes to implement this.

Real code:

. h Files

 @interface ViewController : UIViewController
 @property (nonatomic, strong) IBOutlet UILabel *attrLabel;
 - (IBAction)next:(id)sender;
 @end
The. m file adds the following code to 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;

Effect Chart:

If you want to implement this effect in a previous version of iOS6.0, you need to use a Third-party library Tttattributedlabel, as well as an import coretext.frame framework.

Second, the use of runtime Global modify Uilabel default font
This is the simplest and easiest way, and we can use the runtime mechanism to replace the Uilabel initialization method, where the label's font is set by default. Because the label can be initialized from three sources of initWithFrame, init, and nib files, we need to replace the three initialization methods.

First, we create a uilabel category:

#import <UIKit/UIKit.h>

@interface UILabel (YHBaseChangeDefaultFont)

@end
Add the following code:

#import "Uilabel+yhbasechangedefaultfont.h"
#import <objc/runtime.h>
@implementation Uilabel (Yhbasechangedefaultfont)
/**
* Each NSObject subclass will invoke the following method to replace the Init method here, using our new font
* If the font is specially set in the program, the specially set font will not be affected, but do not set the font in the label's Init method
* Both the init and initWithFrame and nib file loading methods support replacing the default font
*/
+ (void) load{
Perform this method only once
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
Class class = [self class];
When swizzling a class method, use the following:
Class class = Object_getclass ((id) self);
Replace three methods
SEL originalselector = @selector (init);
SEL OriginalSelector2 = @selector (initwithframe:);
SEL OriginalSelector3 = @selector (awakefromnib);
SEL swizzledselector = @selector (yhbaseinit);
SEL SwizzledSelector2 = @selector (yhbaseinitwithframe:);
SEL SwizzledSelector3 = @selector (yhbaseawakefromnib);


Method Originalmethod = Class_getinstancemethod (class, Originalselector);
Method ORIGINALMETHOD2 = Class_getinstancemethod (class, OriginalSelector2);
Method originalMethod3 = Class_getinstancemethod (class, OriginalSelector3);
Method Swizzledmethod = Class_getinstancemethod (class, Swizzledselector);
Method SWIZZLEDMETHOD2 = Class_getinstancemethod (class, SwizzledSelector2);
Method swizzledMethod3 = Class_getinstancemethod (class, SwizzledSelector3);
BOOL Didaddmethod =
Class_addmethod (class,
Originalselector,
Method_getimplementation (Swizzledmethod),
Method_gettypeencoding (Swizzledmethod));
BOOL DIDADDMETHOD2 =
Class_addmethod (class,
OriginalSelector2,
Method_getimplementation (SWIZZLEDMETHOD2),
Method_gettypeencoding (SWIZZLEDMETHOD2));
BOOL didAddMethod3 =
Class_addmethod (class,
OriginalSelector3,
Method_getimplementation (SWIZZLEDMETHOD3),
Method_gettypeencoding (SWIZZLEDMETHOD3));

if (Didaddmethod) {
Class_replacemethod (class,
Swizzledselector,
Method_getimplementation (Originalmethod),
Method_gettypeencoding (Originalmethod));

} else {
Method_exchangeimplementations (Originalmethod, Swizzledmethod);
}
if (DIDADDMETHOD2) {
Class_replacemethod (class,
SwizzledSelector2,
Method_getimplementation (ORIGINALMETHOD2),
Method_gettypeencoding (ORIGINALMETHOD2));
}else {
Method_exchangeimplementations (ORIGINALMETHOD2, SWIZZLEDMETHOD2);
}
if (didAddMethod3) {
Class_replacemethod (class,
SwizzledSelector3,
Method_getimplementation (ORIGINALMETHOD3),
Method_gettypeencoding (ORIGINALMETHOD3));
}else {
Method_exchangeimplementations (originalMethod3, swizzledMethod3);
}
});

}
/**
* Change your font name in these methods
*/
-(Instancetype) Yhbaseinit
{
ID __self = [self yhbaseinit];
Uifont * Font = [Uifont fontwithname:@ "Here Enter your font name" size:self.font.pointSize];
if (font) {
Self.font=font;
}
return __self;
}

-(instancetype)YHBaseInitWithFrame:(CGRect)rect{
    id __self = [self YHBaseInitWithFrame:rect];
    UIFont * font = [UIFont fontWithName:@"这里输入你的字体名字" size:self.font.pointSize];
    if (font) {
        self.font=font;
    }
    return __self;
}
-(void)YHBaseAwakeFromNib{
    [self YHBaseAwakeFromNib];
    UIFont * font = [UIFont fontWithName:@"这里输入你的字体名字" size:self.font.pointSize];
    if (font) {
        self.font=font;
    }
   
}

@end
To write the font we want to uilabel the default display in the above method, we create a uilabel from Init,initwithframe and nib files and add them to the view without any other action:

UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, 100, 280, 30)];
    label.text = @"你是从initWithFrame来的label";
    UILabel * label2 = [[UILabel alloc]init];
    label2.frame= CGRectMake(20, 200, 280, 30);
    label2.text = @"你是从init来的label";
    [self.view addSubview:label];
    [self.view addSubview:label2];

The operating effect is as follows, you can see that the fonts are all replaced:

Related Article

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.