如何在ios应用程序中将自定义字体系列设置为系统字体

时间:2013-10-23 13:24:29

标签: ios fonts uiapplication

我正在开发一个ios应用程序,我必须在UI中使用自定义字体。 我知道如何在应用程序中集成新的自定义字体。为此我有

  1. 使用.ttf扩展名下载字体系列文件。
  2. 将它们添加到资源包中。
  3. 在info.plist文件中添加应用程序提供的关键字体。
  4. 此自定义字体显示效果。但我想要做的是,我想将它们设置为systemFont。所以我不必在所有UI元素中设置它们。

    我想要像

    这样的东西
    [[UIApplication sharedApplication] systemFont:@"Arial"];
    

    这可能吗?任何人都能帮助我吗?

1 个答案:

答案 0 :(得分:16)

在为iOS 7更新我的iOS应用程序时遇到了同样的问题。我想为整个应用程序设置自定义字体,即使对于不允许自定义字体的控件(例如拣货员)也是如此。
经过对网络和Twitter的一些研究后,我解决了使用Method Swizzling的做法,这是一种交换方法实现的做法。

注意:如果不小心使用,此方法可能会有危险!阅读关于SO的讨论:Dangers of Method Swizzling

但是,这是做什么的:

  1. 创建UIFont类别,例如UIFont + CustomSystemFont。
  2. 在.m文件中导入<objc/runtime.h>
  3. 保留.h文件未修改,并将此代码添加到.m:
  4. +(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);
    }
    
相关问题