为整个iOS应用设置默认字体?

时间:2012-01-03 01:44:57

标签: ios fonts

我有一个自定义字体,我想用于在我的应用,标签,文字视图等中显示文字的所有内容。

有没有办法为整个应用设置默认字体(默认标签使用SystemFont)?

17 个答案:

答案 0 :(得分:157)

在iOS 5中似乎可以使用UIAppearance代理。

 [[UILabel appearance] setFont:[UIFont fontWithName:@"YourFontName" size:17.0]];

这会将字体设置为应用中所有UILabel的自定义字体。你需要为每个控件(UIButton,UILabel等)重复它。

请记住,您需要将UIAppFonts值放在info.plist中,并包含您所包含字体的名称。

答案 1 :(得分:87)

Swift 4.1

根据FábioOliveira的回答(https://stackoverflow.com/a/23042694/2082851),我自己动手4。

简而言之,此扩展程序使用我的自定义方法交换默认函数init(coder:)systemFont(ofSize:)boldSystemFont(ofSize:)italicSystemFont(ofSize:)

请注意,它并未完全实现,但您可以根据我的实现交换更多方法。

import UIKit

struct AppFontName {
    static let regular = "CourierNewPSMT"
    static let bold = "CourierNewPS-BoldMT"
    static let italic = "CourierNewPS-ItalicMT"
}

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

extension UIFont {

    @objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.regular, size: size)!
    }

    @objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.bold, size: size)!
    }

    @objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: AppFontName.italic, size: size)!
    }

    @objc convenience init(myCoder aDecoder: NSCoder) {
        guard
            let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
            let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
                self.init(myCoder: aDecoder)
                return
        }
        var fontName = ""
        switch fontAttribute {
        case "CTFontRegularUsage":
            fontName = AppFontName.regular
        case "CTFontEmphasizedUsage", "CTFontBoldUsage":
            fontName = AppFontName.bold
        case "CTFontObliqueUsage":
            fontName = AppFontName.italic
        default:
            fontName = AppFontName.regular
        }
        self.init(name: fontName, size: fontDescriptor.pointSize)!
    }

    class func overrideInitialize() {
        guard self == UIFont.self else { return }

        if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
            let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
            method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
        }

        if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
            let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
            method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
        }

        if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
            let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
            method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
        }

        if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))), // Trick to get over the lack of UIFont.init(coder:))
            let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
            method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
        }
    }
}


class AppDelegate: UIResponder, UIApplicationDelegate {
    // Avoid warning of Swift
    // Method 'initialize()' defines Objective-C class method 'initialize', which is not guaranteed to be invoked by Swift and will be disallowed in future versions
    override init() {
        super.init()
        UIFont.overrideInitialize()
    }
    ...
}

答案 2 :(得分:74)

还有另一种解决方法是覆盖systemFont。

只需创建一个类别

<强> UIFont + SystemFontOverride.h

#import <UIKit/UIKit.h>

@interface UIFont (SystemFontOverride)
@end

<强> UIFont + SystemFontOverride.m

@implementation UIFont (SystemFontOverride)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"

+ (UIFont *)boldSystemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

+ (UIFont *)systemFontOfSize:(CGFloat)fontSize {
    return [UIFont fontWithName:@"fontName" size:fontSize];
}

#pragma clang diagnostic pop

@end

这将取代默认实现,大多数UIControl使用systemFont。

答案 3 :(得分:60)

如果你正在使用Swift,你可以创建一个UILabel扩展名:

extension UILabel {

    var substituteFontName : String {
        get { return self.font.fontName }
        set { self.font = UIFont(name: newValue, size: self.font.pointSize) }
    }

}

然后你在哪里做你的外表代理:

UILabel.appearance().substituteFontName = applicationFont

在名为UI_APPEARANCE_SELECTOR的属性上使用substituteFontName存在等效的Objective-C代码。

<强>加成

对于您想要分别设置粗体和常规字体的情况:

extension UILabel {

    var substituteFontName : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.range(of:"Medium") == nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }

    var substituteFontNameBold : String {
        get { return self.font.fontName }
        set { 
            if self.font.fontName.range(of:"Medium") != nil { 
                self.font = UIFont(name: newValue, size: self.font.pointSize)
            }
        }
    }
}

然后为您的UIAppearance代理:

UILabel.appearance().substituteFontName = applicationFont
UILabel.appearance().substituteFontNameBold = applicationFontBold

注意:如果您发现粗体替换不起作用,则默认字体名称可能不包含&#34; Medium&#34;。根据需要将该字符串切换为另一场比赛(感谢Mason在下面的评论中)。

答案 4 :(得分:22)

从Hugues BR开始回答但是使用方法调整我已经找到了一个解决方案,它成功地将所有字体更改为我应用中的所需字体。

使用动态类型的方法应该是您在iOS 7上应该寻找的方法。以下解决方案不使用动态类型。


注意:

  • 以下代码处于呈现状态,从未提交Apple批准;
  • 有一个较短的版本通过Apple提交,没有- initWithCoder:覆盖。但是,这不会涵盖所有情况;
  • 以下代码出现在我用来设置app的样式的类中,该样式由我的AppDelegate类包含,因此可以在任何地方和所有UIFont实例中使​​用;
  • 我在这里使用Zapfino只是为了让更改更加明显;
  • 欢迎您对此代码进行任何改进。

此解决方案使用两种不同的方法来实现最终结果。第一个是覆盖UIFont类方法+ systemFontWithSize:,类似于使用我的替代方法(这里我使用“Zapfino”毫无疑问替换是成功的。)

另一种方法是覆盖UIFont上的- initWithCoder:方法,以替换任何出现的CTFontRegularUsage和类似的替代方法。 最后一种方法是必要的,因为我发现在NIB文件中编码的UILabel对象不检查+ systemFontWithSize:方法以获取其系统字体,而是将它们编码为UICTFontDescriptor个对象。 我试图覆盖- awakeAfterUsingCoder:,但不知怎的,我的故事板中的每个编码对象都被调用并导致崩溃。覆盖- awakeFromNib将不允许我阅读NSCoder对象。

#import <objc/runtime.h>

NSString *const FORegularFontName = @"Zapfino";
NSString *const FOBoldFontName = @"Zapfino";
NSString *const FOItalicFontName = @"Zapfino";

#pragma mark - UIFont category
@implementation UIFont (CustomFonts)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (void)replaceClassSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
    Method originalMethod = class_getClassMethod(self, originalSelector);
    Method modifiedMethod = class_getClassMethod(self, modifiedSelector);
    method_exchangeImplementations(originalMethod, modifiedMethod);
}

+ (void)replaceInstanceSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
    Method originalDecoderMethod = class_getInstanceMethod(self, originalSelector);
    Method modifiedDecoderMethod = class_getInstanceMethod(self, modifiedSelector);
    method_exchangeImplementations(originalDecoderMethod, modifiedDecoderMethod);
}

+ (UIFont *)regularFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:FORegularFontName size:size];
}

+ (UIFont *)boldFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:FOBoldFontName size:size];
}

+ (UIFont *)italicFontOfSize:(CGFloat)fontSize
{
    return [UIFont fontWithName:FOItalicFontName size:fontSize];
}

- (id)initCustomWithCoder:(NSCoder *)aDecoder {
    BOOL result = [aDecoder containsValueForKey:@"UIFontDescriptor"];

    if (result) {
        UIFontDescriptor *descriptor = [aDecoder decodeObjectForKey:@"UIFontDescriptor"];

        NSString *fontName;
        if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontRegularUsage"]) {
            fontName = FORegularFontName;
        }
        else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontEmphasizedUsage"]) {
            fontName = FOBoldFontName;
        }
        else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontObliqueUsage"]) {
            fontName = FOItalicFontName;
        }
        else {
            fontName = descriptor.fontAttributes[@"NSFontNameAttribute"];
        }

        return [UIFont fontWithName:fontName size:descriptor.pointSize];
    }

    self = [self initCustomWithCoder:aDecoder];

    return self;
}

+ (void)load
{
    [self replaceClassSelector:@selector(systemFontOfSize:) withSelector:@selector(regularFontWithSize:)];
    [self replaceClassSelector:@selector(boldSystemFontOfSize:) withSelector:@selector(boldFontWithSize:)];
    [self replaceClassSelector:@selector(italicSystemFontOfSize:) withSelector:@selector(italicFontOfSize:)];

    [self replaceInstanceSelector:@selector(initWithCoder:) withSelector:@selector(initCustomWithCoder:)];
}
#pragma clang diagnostic pop

@end

答案 5 :(得分:13)

要完成Sandy Chapman's answer,这是Objective-C中的解决方案(将此类别放在您想要更改的任何位置UILabel Appearance):

@implementation UILabel (FontOverride)
- (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR {
    self.font = [UIFont fontWithName:name size:self.font.pointSize];
}
@end

接口文件应该公开声明此方法,以便稍后从app delegate:

这样的地方使用
@interface UILabel (FontOverride)
  - (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR;
@end

然后,您可以使用以下内容更改Appearance

[[UILabel appearance] setSubstituteFontName:@"SourceSansPro-Light"];

答案 6 :(得分:4)

适用于Swift 4

以上所有答案都是正确的,但我采用的方式略有不同,根据设备尺寸。 在这里,在ATFontManager类中,我已经将默认字体大小定义在类的顶部,作为 defaultFontSize ,这是字体大小 iphone plus ,您可以根据自己的要求进行更改。

     class ATFontManager: UIFont{

    class func setFont( _ iPhone7PlusFontSize: CGFloat? = nil,andFontName fontN : String = FontName.HelveticaNeue) -> UIFont{

        let defaultFontSize : CGFloat = 16

        switch ATDeviceDetector().screenType {

        case .iPhone4:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize - 3)!
            }
            return UIFont(name: fontN, size: defaultFontSize - 6)!

        case .iPhone5:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize - 2)!
            }
            return UIFont(name: fontN, size: defaultFontSize - 3)!

        case .iPhone6AndIphone7:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize - 1)!
            }
            return UIFont(name: fontN, size: defaultFontSize - 1)!

        case .iPhone6PAndIPhone7P:

            return UIFont(name: fontN, size: iPhone7PlusFontSize ?? defaultFontSize)!
        case .iPhoneX:

            return UIFont(name: fontN, size: iPhone7PlusFontSize ?? defaultFontSize)!

        case .iPhoneOrIPadSmallSizeUnknown:

            return UIFont(name: fontN, size: iPhone7PlusFontSize ?? defaultFontSize)!

        case .iPadMini:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize + 4)!
            }
            return UIFont(name: fontN, size: defaultFontSize + 4)!

        case .iPadPro10Inch:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize + 5)!
            }
            return UIFont(name: fontN, size: defaultFontSize + 5)!

        case .iPadPro:
            if let fontSize = iPhone7PlusFontSize{
                return UIFont(name: fontN, size: fontSize + 6)!
            }
            return UIFont(name: fontN, size: defaultFontSize + 6)!

        case .iPadUnknown:

            return UIFont(name: fontN, size: defaultFontSize + 3)!

        default:

            return UIFont(name: fontN, size: iPhone7PlusFontSize ?? 15)!
        }
    }
}

我添加了某些字体名称,您可以在此处添加字体名称和类型。

   enum FontName : String {
        case HelveticaNeue = "HelveticaNeue"
        case HelveticaNeueUltraLight = "HelveticaNeue-UltraLight"
        case HelveticaNeueBold = "HelveticaNeue-Bold"
        case HelveticaNeueBoldItalic = "HelveticaNeue-BoldItalic"
        case HelveticaNeueMedium = "HelveticaNeue-Medium"
        case AvenirBlack = "Avenir-Black"
        case ArialBoldMT = "Arial-BoldMT"
        case HoeflerTextBlack = "HoeflerText-Black"
        case AMCAPEternal = "AMCAPEternal"
    }

此类指设备检测器,以便根据设备提供适当的字体大小。

class ATDeviceDetector {

    var iPhone: Bool {

        return UIDevice().userInterfaceIdiom == .phone
    }

    var ipad : Bool{

        return UIDevice().userInterfaceIdiom == .pad
    }

    let isRetina = UIScreen.main.scale >= 2.0


    enum ScreenType: String {

        case iPhone4
        case iPhone5
        case iPhone6AndIphone7
        case iPhone6PAndIPhone7P
        case iPhoneX

        case iPadMini
        case iPadPro
        case iPadPro10Inch

        case iPhoneOrIPadSmallSizeUnknown
        case iPadUnknown
        case unknown
    }


    struct ScreenSize{

        static let SCREEN_WIDTH         = UIScreen.main.bounds.size.width
        static let SCREEN_HEIGHT        = UIScreen.main.bounds.size.height
        static let SCREEN_MAX_LENGTH    = max(ScreenSize.SCREEN_WIDTH,ScreenSize.SCREEN_HEIGHT)
        static let SCREEN_MIN_LENGTH    = min(ScreenSize.SCREEN_WIDTH,ScreenSize.SCREEN_HEIGHT)
    }


    var screenType: ScreenType {

        switch ScreenSize.SCREEN_MAX_LENGTH {

        case 0..<568.0:
            return .iPhone4
        case 568.0:
            return .iPhone5
        case 667.0:
            return .iPhone6AndIphone7
        case 736.0:
            return .iPhone6PAndIPhone7P
        case 812.0:
            return .iPhoneX
        case 568.0..<812.0:
            return .iPhoneOrIPadSmallSizeUnknown
        case 1112.0:
            return .iPadPro10Inch
        case 1024.0:
            return .iPadMini
        case 1366.0:
            return .iPadPro
        case 812.0..<1366.0:
            return .iPadUnknown
        default:
            return .unknown
        }
    }
}

如何使用。希望它会有所帮助。

//for default 
label.font = ATFontManager.setFont()

//if you want to provide as your demand. Here **iPhone7PlusFontSize** variable is denoted as font size for *iphone 7plus and iphone 6 plus*, and it **ATFontManager** class automatically handle.
label.font = ATFontManager.setFont(iPhone7PlusFontSize: 15, andFontName: FontName.HelveticaNeue.rawValue)

答案 7 :(得分:4)

对SWIFT 3.0和SWIFT警告的评论

您可以删除警告信息:

let initCoderMethod = class_getInstanceMethod(self, Selector("initWithCoder:"))

将其替换为:

let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:)))

答案 8 :(得分:3)

字体类型始终在代码和nib / storyboard中设置。

对于代码,就像Hugues BR said一样,在catagory中执行此操作可以解决问题。

对于nib / storyboard,我们可以通过Swizzling awakeFromNib来改变字体类型,因为nib / storyboard中的UI元素总是在屏幕中显示之前调用它。

我想你知道Aspects。它是一个基于Method Swizzling的AOP编程库。 我们为UILabel,UIButton,UITextView创建了实现它的类别。

的UILabel:

#import "UILabel+OverrideBaseFont.h"
#import "Aspects.h"

@implementation UILabel (OverrideBaseFont)

+ (void)load {
    [[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
        UILabel* instance = [aspectInfo instance];
        UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
        instance.font = font;
    }error:nil];
}

@end

UIButton:

#import "UIButton+OverrideBaseFont.h"
#import "Aspects.h"

@implementation UIButton (OverrideBaseFont)

+ (void)load {
    [[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
        UIButton* instance = [aspectInfo instance];
        UILabel* label = instance.titleLabel;
        UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:label.font.pointSize];
        instance.titleLabel.font = font;
    }error:nil];
}

@end

的UITextField:

#import "UITextField+OverrideBaseFont.h"
#import "Aspects.h"

@implementation UITextField (OverrideBaseFont)

+ (void)load {
    [[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
        UITextField* instance = [aspectInfo instance];
        UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
        instance.font = font;
    }error:nil];
}

@end

的UITextView:

#import "UITextView+OverrideBaseFont.h"
#import "Aspects.h"

@implementation UITextView (OverrideBaseFont)

+ (void)load {
    [[self class]aspect_hookSelector:@selector(awakeFromNib) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> aspectInfo) {
        UITextView* instance = [aspectInfo instance];
        UIFont* font = [UIFont fontWithName:@"HelveticaNeue-light" size:instance.font.pointSize];
        instance.font = font;
    }error:nil];
}

@end

就是这样,您可以使用您的字体名称将HelveticaNeue-light更改为宏。

答案 9 :(得分:3)

这些解决方案都不适用于整个应用程序。我发现有助于管理Xcode中的字体的一件事是打开Storyboard作为源代码(在文件导航器中按住Control键单击故事板&gt;&#34;打开为&#34;&gt;&#34;来源&#34;),以及然后进行查找和替换。

答案 10 :(得分:2)

可能不是,您可能会自己设置控件上的字体,但是您可以通过集中从哪里获取字体类型来简化过程,例如让app委托或其他公共类具有方法返回字体,任何需要设置字体的东西都可以调用该方法,这将有助于您需要更改字体,您可以在一个地方而不是在设置字体的任何地方更改它...另一种选择可以是制作你自己设置字体的UI元素的子类,但这可能有点过分..

答案 11 :(得分:2)

在查看了几篇文章后,我为 Swift 4 创建了自己的字体转换,它涵盖了大多数情况,例如:

struct Resources {

    struct Fonts {
        //struct is extended in Fonts
    }
}

extension Resources.Fonts {

    enum Weight: String {
        case light = "Typo-Light"
        case regular = "Typo-Regular"
        case semibold = "Typo-Semibold"
        case italic = "Typo-LightItalic"
    }
}

extension UIFontDescriptor.AttributeName {
    static let nsctFontUIUsage = UIFontDescriptor.AttributeName(rawValue: "NSCTFontUIUsageAttribute")
}

extension UIFont {

    @objc class func mySystemFont(ofSize: CGFloat, weight: UIFont.Weight) -> UIFont {
        switch weight {
        case .semibold, .bold, .heavy, .black:
            return UIFont(name: Resources.Fonts.Weight.semibold.rawValue, size: ofSize)!

        case .medium, .regular:
            return UIFont(name: Resources.Fonts.Weight.regular.rawValue, size: ofSize)!

        default:
            return UIFont(name: Resources.Fonts.Weight.light.rawValue, size: ofSize)!
        }
    }

    @objc class func mySystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.light.rawValue, size: size)!
    }

    @objc class func myBoldSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.semibold.rawValue, size: size)!
    }

    @objc class func myItalicSystemFont(ofSize size: CGFloat) -> UIFont {
        return UIFont(name: Resources.Fonts.Weight.italic.rawValue, size: size)!
    }

    @objc convenience init(myCoder aDecoder: NSCoder) {
        guard
            let fontDescriptor = aDecoder.decodeObject(forKey: "UIFontDescriptor") as? UIFontDescriptor,
            let fontAttribute = fontDescriptor.fontAttributes[.nsctFontUIUsage] as? String else {
                self.init(myCoder: aDecoder)
                return
        }
        var fontName = ""
        switch fontAttribute {
        case "CTFontRegularUsage", "CTFontMediumUsage":
            fontName = Resources.Fonts.Weight.regular.rawValue
        case "CTFontEmphasizedUsage", "CTFontBoldUsage", "CTFontSemiboldUsage","CTFontHeavyUsage", "CTFontBlackUsage":
            fontName = Resources.Fonts.Weight.semibold.rawValue
        case "CTFontObliqueUsage":
            fontName = Resources.Fonts.Weight.italic.rawValue
        default:
            fontName = Resources.Fonts.Weight.light.rawValue
        }
        self.init(name: fontName, size: fontDescriptor.pointSize)!
    }

    class func overrideDefaultTypography() {
        guard self == UIFont.self else { return }

        if let systemFontMethodWithWeight = class_getClassMethod(self, #selector(systemFont(ofSize: weight:))),
            let mySystemFontMethodWithWeight = class_getClassMethod(self, #selector(mySystemFont(ofSize: weight:))) {
            method_exchangeImplementations(systemFontMethodWithWeight, mySystemFontMethodWithWeight)
        }

        if let systemFontMethod = class_getClassMethod(self, #selector(systemFont(ofSize:))),
            let mySystemFontMethod = class_getClassMethod(self, #selector(mySystemFont(ofSize:))) {
            method_exchangeImplementations(systemFontMethod, mySystemFontMethod)
        }

        if let boldSystemFontMethod = class_getClassMethod(self, #selector(boldSystemFont(ofSize:))),
            let myBoldSystemFontMethod = class_getClassMethod(self, #selector(myBoldSystemFont(ofSize:))) {
            method_exchangeImplementations(boldSystemFontMethod, myBoldSystemFontMethod)
        }

        if let italicSystemFontMethod = class_getClassMethod(self, #selector(italicSystemFont(ofSize:))),
            let myItalicSystemFontMethod = class_getClassMethod(self, #selector(myItalicSystemFont(ofSize:))) {
            method_exchangeImplementations(italicSystemFontMethod, myItalicSystemFontMethod)
        }

        if let initCoderMethod = class_getInstanceMethod(self, #selector(UIFontDescriptor.init(coder:))),
            let myInitCoderMethod = class_getInstanceMethod(self, #selector(UIFont.init(myCoder:))) {
            method_exchangeImplementations(initCoderMethod, myInitCoderMethod)
        }
    }
}

最后在Appdelegate处调用创建的方法,如下所示:

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

        UIFont.overrideDefaultTypography()
        return true
    }
}

答案 12 :(得分:1)

NUI是UIAppearance代理的替代方案。它允许您通过简单地修改样式表来控制整个应用程序中大量UI元素类型的字体(以及许多其他属性),该样式表可以在多个应用程序中重用。

在标签中添加NUILabel课程后,您可以轻松地在样式表中控制其字体:

LabelFontName    String    Helvetica

如果您有不同字体大小的标签,您可以使用NUI的Label,LargeLabel和SmallLabel类控制它们的大小,甚至可以快速创建自己的类。

答案 13 :(得分:0)

在swift中使用这种类型的字体类。使用字体扩展类。

enum FontName: String {

  case regular      = "Roboto-Regular"

}

//MARK: - Set Font Size
enum FontSize: CGFloat {
    case size = 10

}
extension UIFont {

    //MARK: - Bold Font
  class var regularFont10: UIFont {
        return UIFont(name: FontName.regular.rawValue, size:FontSize.size.rawValue )!
    }
}

答案 14 :(得分:0)

对于AppDelegate的FinishedLaunching()中的Xamarin.iOS,代码如下:-

UILabel.Appearance.Font= UIFont.FromName("Lato-Regular", 14);

为整个应用程序设置字体,然后在Info.plist上添加'UIAppFonts'键,该路径应为字体文件.ttf所在的路径。对我来说,它位于我的'fonts'文件夹中项目。

<key>UIAppFonts</key>
    <array>
        <string>fonts/Lato-Regular.ttf</string>
    </array>

答案 15 :(得分:0)

@Randall提到,iOS 5.0+ UIApperance代理可用于自定义类read more的所有实例的外观。

Xcodes自动完成功能不会显示所有可用的属性,并且可能会引发错误,但是您只需将其键入即可编译。

UILabel.apperance().font = UIFont.systemFont(ofSize: 17, weight: .regular)

答案 16 :(得分:-1)

我们使用父视图控制器和子视图控制器(继承)在Swift -Xcode 7.2中实现了相同的功能。

File - New - Cocoa Touch类 - ParentViewController。

    import UIKit
    import Foundation

    class ParentViewController: UIViewController {

        var appUIColor:UIColor = UIColor.redColor()
        var appFont:UIFont = UIFont(name: "Copperplate", size: 20)!

        override func viewDidLoad() {
            super.viewDidLoad()
        }
        func addStatusBar()
        {
            let view = UIView(frame:
                CGRect(x: 0.0, y: 0.0, width: UIScreen.mainScreen().bounds.size.width, height: 20.0)
            )
            view.backgroundColor = appUIColor
            self.view.addSubview(view)
        }
    }    

创建子视图控制器并与StoryBoard VC关联,添加textLabel。

    import UIKit

    class FontTestController: ParentViewController {
        @IBOutlet var testLabel: UILabel!

        override func viewDidLoad() {
            super.viewDidLoad()
            testLabel.font =  appFont
            testLabel.textColor = appUIColor
        }

或制作自定义UILabel类(子分类方法)并将所需标签与其关联。

import Foundation
import UIKit

class CustomFontLabel: UILabel {
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        backgroundColor = ParentViewController().appUIColor
        font = ParentViewController().appFont
        textColor = UIColor.blackColor()
    }
}

注意:在父VC中声明的字体和颜色在CustomFontLabel中实现。优点是我们可以在父VC中的一些简单更改中一起更改uilabel /任何视图的属性。

2)&#39;对于&#39;为子视图循环UIView。它仅适用于特定的VC。

    override func viewWillLayoutSubviews() {
            for view in self.view.subviews  {
                if view.isKindOfClass(UITextField) {
                UITextField.appearance().font =  UIFont(name: "Copperplate", size: 20)
                }
                if view.isKindOfClass(UILabel) {
                    UILabel.appearance().font =  UIFont(name: "Copperplate", size: 20)    
                }               
            }       
        }