Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom font family as system font in ios application [duplicate]

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?

like image 498
Jay Pandya Avatar asked Oct 23 '13 13:10

Jay Pandya


1 Answers

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);
}
like image 163
matteodv Avatar answered Sep 21 '22 15:09

matteodv