change fonts with runtime one click in iOS

Source: Internet
Author: User

Http://www.cocoachina.com/ios/20160504/16109.html

This article is a contributing article, Henrycheng (Pinterest)

Recently the company is going to hold a large conference in May, so before this will be a stable version, interface upgrade, so there are a lot of deliberately to do. However, while the previous two days of the release just submitted to the line, these two days a little idle, the previous said the use of a button to change the font of the way to share. Some people will say, change the font is not very simple, I directly find the font name to replace it is not good? Sir don't hurry, sit down and eat some melon seeds, listen to me slowly to you.

1. Preparation

We created a new project called Changefont, and then I casually found a name Loveway.ttf the font library dragged in, inside the project directory is probably the case

Directory

Now we simply drag a label directly on the storyboard a button, constrained, like this

Storyboard

Well, that's it, very simple, run

Run results

Good show normal, no problem, then change the font.

2. Change the font

We have already dragged the Loveway.ttf file in, and now configure it in the Plist file. Open plist and add a line called fonts provided by application to add our font names to the item.

Plist

In the end, we need to make sure we're actually adding in.

Phases

This time maybe you can't wait, quickly change the font, as follows

1234567891011121314151617181920212223 ////  ViewController.m//  ChangeFont////  Created by HenryCheng on 16/4/27.//  Copyright 2016年 HenryCheng. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *myLabel;@property (weak, nonatomic) IBOutlet UIButton *myButton;@end@implementation ViewController- (void)viewDidLoad {    [superviewDidLoad];    _myLabel.font = [UIFont fontWithName:@"loveway.ttf"size:17.0f];    _myButton.titleLabel.font = [UIFont fontWithName:@"loveway"size:17.0f];}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

Run... Oh no! How did not change, or the original appearance?!

Must be posture is not right, so Baidu a bit (although I generally use Google), indeed this method is not correct.

So change the idea, first find the name of the font, like this, the code changed to this

1234567891011 - (void)viewDidLoad {    [superviewDidLoad];    for(NSString *familyName in[UIFont familyNames]){        NSLog(@"Font FamilyName = %@",familyName); //*输出字体族科名字        for(NSString *fontName in[UIFont fontNamesForFamilyName:familyName]) {            NSLog(@"\t%@",fontName);         //*输出字体族科下字样名字        }    }    _myLabel.font = [UIFont fontWithName:@"loveway.ttf"size:17.0f];    _myButton.titleLabel.font = [UIFont fontWithName:@"loveway"size:17.0f];}

Run a look at the console

The font name portion of the output

What the hell, I don't know what the name of the font I just added.

So came up with a way to build a project, do not add Loveway.ttf this font, print out, a comparison, many of that is it! Bingo, so spent a while kung Fu finally find out, is fzlbjw--gb1-0, regardless of, first try it OK

1234567891011121314 ![](http://upload-images.jianshu.io/upload_images/571495-b0d97825e5d33a8a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)- (void)viewDidLoad {    [superviewDidLoad];    /*    for(NSString *familyName in [UIFont familyNames]){        NSLog(@"Font FamilyName = %@",familyName); //输出字体族科名字        for(NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {            NSLog(@"\t%@",fontName);         //输出字体族科下字样名字        }    }     */    _myLabel.font = [UIFont fontWithName:@"FZLBJW--GB1-0"size:17.0f];    _myButton.titleLabel.font = [UIFont fontWithName:@"FZLBJW--GB1-0"size:17.0f];}

Run, the results are as follows

Run results after changing the font

Ok! Reach the effect, although a bit of frustration, but the effect achieved, but also good.

Here, the basic change font effect has been achieved.

3. A simple way to find fonts

In the above we can see, through the method of comparison to find the name fzlbjw--gb1-0, here, there is a simple way, we find this TTF in the Finder, double-click Open (in Xcode double-click Open No effect), this time the system will be with the Apple's own font book opened, As follows:

Use font Book to open. rtf

So we can see the font of the family branch name, we see is fzlibian-s02s, so we just output all the font name of the console search for this family name, you can know the specific font name

Search fzlibian-s02s

This is much simpler than the above.

4. Further thinking

The example above simply said that the way to change the font, although successful, but we have to think about it. The above is just two simple controls, so what if I have a bunch of controls? Or you can say I also use this method to add one by one, if you write pure code is OK, if you write Xib, do you want to put a useless just display the label or button to write it? In this way, the efficiency will certainly be very low, especially those who write half of the big project, it is felt that this method is certainly not feasible.

The Class_addmethod, Class_replacemethod, method_exchangeimplementations methods of the runtime are used here, and then according to the + (void) The feature implementation of load this method (about + (void) Load This method will say, or do not know children's shoes can first look up data), the code is as follows

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 ////  UILabel+FontChange.m//  LiquoriceDoctorProject////  Created by HenryCheng on 15/12/7.//  Copyright ? 2015年 iMac. All rights reserved.//#import "UILabel+FontChange.h"#import <objc runtime.h="">#define CustomFontName @"FZLBJW--GB1-0"@implementation UILabel (FontChange)+ (void)load {    //方法交换应该被保证,在程序中只会执行一次    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{        //获得viewController的生命周期方法的selector        SEL systemSel = @selector(willMoveToSuperview:);        //自己实现的将要被交换的方法的selector        SEL swizzSel = @selector(myWillMoveToSuperview:);        //两个方法的Method        Method systemMethod = class_getInstanceMethod([self class], systemSel);        Method swizzMethod = class_getInstanceMethod([self class], swizzSel);        //首先动态添加方法,实现是被交换的方法,返回值表示添加成功还是失败        BOOL isAdd = class_addMethod(self, systemSel, method_getImplementation(swizzMethod), method_getTypeEncoding(swizzMethod));        if(isAdd) {            //如果成功,说明类中不存在这个方法的实现            //将被交换方法的实现替换到这个并不存在的实现            class_replaceMethod(self, swizzSel, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));        else{            //否则,交换两个方法的实现            method_exchangeImplementations(systemMethod, swizzMethod);        }    });}- (void)myWillMoveToSuperview:(UIView *)newSuperview {    [self myWillMoveToSuperview:newSuperview];//    if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {//        return;//    }    if(self) {        if(self.tag == 10086) {            self.font = [UIFont systemFontOfSize:self.font.pointSize];        else{            if([UIFont fontNamesForFamilyName:CustomFontName])                self.font  = [UIFont fontWithName:CustomFontName size:self.font.pointSize];        }    }}@end</objc>

Then do not add any code as follows

12345678910111213141516171819202122232425262728293031 ////  ViewController.m//  ChangeFont////  Created by HenryCheng on 16/4/27.//  Copyright 2016年 HenryCheng. All rights reserved.//#import "ViewController.h"@interface ViewController ()@property (weak, nonatomic) IBOutlet UILabel *myLabel;@property (weak, nonatomic) IBOutlet UIButton *myButton;@end@implementation ViewController- (void)viewDidLoad {    [superviewDidLoad];//    for(NSString *familyName in [UIFont familyNames]){//        NSLog(@"Font FamilyName = %@",familyName); //输出字体族科名字////        for(NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) {//            NSLog(@"\t%@",fontName);         //输出字体族科下字样名字//        }//    }//    _myLabel.font = [UIFont fontWithName:@"FZLBJW--GB1-0" size:17.0f];//    _myButton.titleLabel.font = [UIFont fontWithName:@"FZLBJW--GB1-0" size:17.0f];//    _myLabel.tag = 10086;}- (void)didReceiveMemoryWarning {    [superdidReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end

Run

We can see that the font has changed.

If someone says I want to change the font some do not want to change the font, I have an easy way to do this is to set the tag, such as I set the label tag 10086 (casually), let his font does not change

Run results

Attention:

1, if you are the code write control, you do not want to change the font, you only need to set the tag at the time of Creation 10086

2, the above code comments a row

123 //if ([self isKindOfClass:NSClassFromString(@"UIButtonLabel")]) {//      return;// }

This is the time when writing does not change the button's title font settings, here you can determine which type of change, for example, you do not want to change the button font, the sentence can be annotated

3, if you are xib pull the control, you do not want to change the font, you have to set the Xib interface tag is 10086, not loaded after the-(void) viewdidload inside the set, this is still because the + (void) Load this method

Before a program (main function) is run, the libraries used are loaded into the runtime, and the +load methods of the classes and categories that are added to the runtime system are called; (It is easy to verify by printing a statement);

If the +load method of the parent class and the subclass is called, the call of the parent class must precede the subclass, which is automatically done by the system, and there is no need to explicitly invoke [super load] in subclass +load;;

This is just a simple way of saying that what you don't understand can be turned over to official documents.

5. Finally

The explanation of the code, in the project has been very clear comments, there is not much to say, not clear children's shoes can give me a message. The exact usage is simple, you just need to pull uilabel+fontchange.h and UILABEL+FONTCHANGE.M into your project.

Need to download more fonts can be downloaded in the Font library, all the code can be downloaded here.

Recently, I've been looking at Swift, taking notes, and we'll share some of the swift tips we've summarized.

Finally, if you have any suggestions or correction of the place please give me a message, if you like or help you, please star a bit, thank you!

change fonts with runtime one click in iOS

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.