首页 文章

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

提问于
浏览
128

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

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

16 回答

  • 0

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

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


    Notes:

    • 以下代码,在其呈现状态下,从未提交给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
    
  • 64

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

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

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

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

  • 2

    还有另一种解决方案是覆盖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 .

  • 58

    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

    如果您使用的是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
    

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

    Addition

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

    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
    

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

  • 1

    要完成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"];
    
  • 155

    我发布它作为新的回复,而不是作为评论,因为我没有足够的声誉 .

    COMMENT FOR SWIFT 3.0 AND SWIFT WARNING

    您可以删除警告消息:

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

    将其替换为:

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

    For Swift 4

    以上所有答案都是正确的,但我的方式与 according to device size 完全不同 . 在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
            }
        }
    }
    

    How to use. 希望它会有所帮助 .

    //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)
    
  • 22

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

  • 0

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

  • 13

    字体类型始终在代码和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更改为宏 .

  • 3

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

    NUILabel 类添加到标签后,您可以轻松控制样式表中的字体:

    LabelFontName    String    Helvetica
    

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

  • 74

    我们使用父视图控制器和子视图控制器(继承)在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)'for'为子视图循环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)    
                    }               
                }       
            }
    
  • 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 )!
        }
    }
    
  • 4

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

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

    设置整个应用程序的字体,并在我的项目中添加' UIAppFonts ' key on Info.plist , the path should be the path where your font file .ttf is situated .For me it was inside ' fonts'文件夹 .

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

    在查看了几篇帖子之后,我创建了自己的排版转换 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
        }
    }
    

相关问题