问题
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
- Download font family files with .ttf extention.
- Add them to resource bundle.
- 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:
- Create a UIFont category, like UIFont+CustomSystemFont.
- Import
<objc/runtime.h>
in your .m file. - 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);
}
来源:https://stackoverflow.com/questions/19542942/how-to-set-custom-font-family-as-system-font-in-ios-application