How to set custom font family as system font in io

2019-02-01 02:56发布

问题:

This question already has an answer here:

  • Set a default font for whole iOS app? 16 answers
  • How can I change default font in ios dev [closed] 1 answer

I am working on an ios application in which i have to use custom fonts for UIs. I know how to integrate new custom fonts in application. For that i have

  1. Download font family files with .ttf extention.
  2. Add them to resource bundle.
  3. In info.plist file add with key Fonts provided by application.

This custom fonts shows effect. But what i want to do is, I want to set them as a systemFont. So i do not have to set them in all UI elements.

I want something like

[[UIApplication sharedApplication] systemFont:@"Arial"];

Is this possible? Can any one help me with this?

回答1:

I had your same problem when updating my iOS app for iOS 7. I wanted to set a custom font for the entire application, even for controls you are not allowed to customize their font (e.g. pickers).
After a bit of research on the web and on Twitter, I solved using Method Swizzling which is a practice that consists in exchanging method implementations.

NOTE: This method might be dangerous if not used carefully! Read this discussion on SO: Dangers of Method Swizzling

However, this is what to do:

  1. Create a UIFont category, like UIFont+CustomSystemFont.
  2. Import <objc/runtime.h> in your .m file.
  3. Leave .h file unmodified and add this code to the .m:
+(UIFont *)regularFontWithSize:(CGFloat)size
{
  return [UIFont fontWithName:@"Your Font Name Here" size:size];
}

+(UIFont *)boldFontWithSize:(CGFloat)size
{
  return [UIFont fontWithName:@"Your Bold Font Name Here" size:size];
}

// Method Swizzling

+(void)load
{
    SEL original = @selector(systemFontOfSize:);
    SEL modified = @selector(regularFontWithSize:);
    SEL originalBold = @selector(boldSystemFontOfSize:);
    SEL modifiedBold = @selector(boldFontWithSize:);

    Method originalMethod = class_getClassMethod(self, original);
    Method modifiedMethod = class_getClassMethod(self, modified);
    method_exchangeImplementations(originalMethod, modifiedMethod);

    Method originalBoldMethod = class_getClassMethod(self, originalBold);
    Method modifiedBoldMethod = class_getClassMethod(self, modifiedBold);
    method_exchangeImplementations(originalBoldMethod, modifiedBoldMethod);
}