Programing

전체 iOS 앱에 기본 글꼴을 설정 하시겠습니까?

lottogame 2020. 6. 12. 22:04
반응형

전체 iOS 앱에 기본 글꼴을 설정 하시겠습니까?


앱의 텍스트, 레이블, 텍스트보기 등을 표시하는 모든 것에 사용하려는 사용자 정의 글꼴이 있습니다.

전체 앱에 기본 글꼴 (기본적으로 레이블은 SystemFont를 사용함)을 설정하는 방법이 있습니까?


iOSAppearance 프록시를 사용하는 iOS 5에서 가능합니다.

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

그러면 글꼴이 앱의 모든 UILabels에 대한 사용자 정의 글꼴이되도록 설정됩니다. 각 컨트롤 (UIButton, UILabel 등)에 대해 반복해야합니다.

info.plist에 UIAppFonts 값을 입력하고 포함하는 글꼴 이름을 포함해야합니다.


스위프트 4.1

Fábio Oliveira의 답변 ( 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()
    }
    ...
}

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를 사용합니다.


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_SELECTORname 속성을 사용하는 동등한 Objective-C 코드가 substituteFontName있습니다.

부가

굵은 글꼴과 일반 글꼴을 별도로 설정하려는 경우 :

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에게 감사드립니다).


Hugues BR 답변에서 개발했지만 방법 스위 즐링을 사용하여 모든 글꼴을 내 앱에서 원하는 글꼴로 성공적으로 변경하는 솔루션에 도달했습니다.

동적 유형을 사용하는 접근 방식은 iOS 7에서 찾아야합니다. 다음 솔루션은 동적 유형을 사용하지 않습니다.


노트:

  • 아래 코드는 제시된 상태에서 Apple의 승인을받지 못했습니다.
  • Apple 제출을 통과 한 더 짧은 버전이 - initWithCoder:있습니다. 즉, 재정의 가 없습니다 . 그러나 모든 경우를 다루지는 않습니다.
  • 다음 코드는 AppDelegate 클래스에 포함 된 내 앱의 스타일을 설정하는 데 사용하는 클래스에 있으며 모든 UIFont 인스턴스에서 사용할 수 있습니다.
  • 여기에서 Zapfino를 사용하여 변경 사항을 훨씬 더 눈에 띄게 만듭니다.
  • 이 코드에 대한 개선 사항은 언제든지 환영합니다.

이 솔루션은 두 가지 방법으로 최종 결과를 얻습니다. 첫 번째는 UIFont 클래스 메소드를 + systemFontWithSize:대체하고 대안을 사용하는 메소드 와 유사합니다 (여기서 "Zapfino"를 사용하여 교체가 성공했는지 의심하지 마십시오).

다른 방법은 - initWithCoder:UIFont의 방법 을 재정 CTFontRegularUsage의하여 대체품으로 발생 하고 유사한 것으로 대체하는 것입니다. 이 마지막 방법은 UILabelNIB 파일로 인코딩 된 객체 + 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

Sandy Chapman의 답변 을 완성하기 위해 Objective-C의 솔루션이 있습니다 (이 카테고리 를 변경하려는 위치에 놓으십시오 UILabel Appearance).

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

인터페이스 파일은이 메소드가 공개적으로 선언되어 나중에 앱 대리자와 같은 장소에서 사용되도록해야합니다.

@interface UILabel (FontOverride)
  - (void)setSubstituteFontName:(NSString *)name UI_APPEARANCE_SELECTOR;
@end

그런 다음로 다음을 변경할 수 있습니다 Appearance.

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

SWIFT 3.0 및 SWIFT 경고에 대한 설명

다음과 같은 경고 메시지를 제거 할 수 있습니다.

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

다음과 같이 바꾸면됩니다 :

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

스위프트 5

위의 모든 대답은 정확하지만 장치 크기에 따라 약간 다른 방식으로 수행했습니다 . 여기, 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 - 5)!
            }
            return UIFont(name: fontN, size: defaultFontSize - 5)!

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

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

        case .iPhone6PAndIPhone7P, .iPhoneUnknownBigSize:

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

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

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

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

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

        case .iPadUnknownSmallSize:

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

        case .iPadUnknownBigSize:

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

        default:

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

특정 글꼴 이름을 추가했습니다. 글꼴 이름과 유형을 여기에 추가 할 수 있습니다.

   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)

이러한 솔루션 중 어느 것도 앱 전체에서 보편적으로 작동하지 않습니다. Xcode에서 글꼴을 관리하는 데 도움이되는 한 가지 이야기는 스토리 보드를 소스 코드로 열고 (파일 탐색기> "다른 이름으로 열기"> "소스"에서 Control- 클릭 스토리 보드) 그런 다음 찾기 및 바꾸기를 수행하는 것입니다.


글꼴 유형은 항상 코드 및 펜촉 / 스토리 보드에서 설정됩니다.

Hugues BR이 말했듯 이 코드의 경우 범주에서 수행하면 문제를 해결할 수 있습니다.

펜촉 / 스토리 보드의 경우 펜촉 / 스토리 보드의 UI 요소가 항상 화면에 표시되기 전에이를 호출하므로 글꼴 유형을 변경하기 위해 awakeFromNib를 스위블 할 수 있습니다.

나는 당신이 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를 글꼴 이름을 가진 매크로로 변경할 수 있습니다.


몇 가지 게시물을 검토 한 후 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
    }
}

아마도 그렇지 않을 것입니다. 컨트롤에 글꼴을 직접 설정했을 수도 있지만 글꼴 유형을 가져 오는 위치를 중앙 집중화하여 프로세스를 쉽게 만들 수 있습니다 (예 : 앱 대리자 또는 다른 일반 클래스에 글꼴 및 글꼴을 설정 해야하는 모든 것이 해당 메소드를 호출 할 수 있습니다. 글꼴을 변경 해야하는 경우 글꼴을 설정하는 곳이 아닌 한 곳에서 글꼴을 변경하는 데 도움이됩니다 ... 또 다른 대안은 글꼴을 자동으로 설정하지만 너무 과도 할 수있는 UI 요소


NUI 는 UIAppearance 프록시의 대안입니다. 여러 애플리케이션에서 재사용 할 수있는 스타일 시트를 수정하여 애플리케이션 전체에서 많은 UI 요소 유형의 글꼴 (및 기타 여러 속성)을 제어 할 수 있습니다.

NUILabel레이블에 클래스를 추가 한 후 스타일 시트에서 해당 글꼴을 쉽게 제어 할 수 있습니다.

LabelFontName    String    Helvetica

글꼴 크기가 다른 레이블이있는 경우 NUI의 Label, LargeLabel 및 SmallLabel 클래스를 사용하여 크기를 제어하거나 자신 만의 클래스를 빠르게 만들 수도 있습니다.


이 유형의 글꼴 클래스를 신속하게 사용하고 있습니다. 폰트 확장 클래스를 사용합니다.

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 )!
    }
}

AppDelegate의 Xamarin.iOS의 경우 다음 FinishedLaunching()과 같은 코드를 넣습니다.

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

전체 응용 프로그램의 글꼴을 설정 UIAppFonts하고 Info.plist에서 ' '키를 추가 하면 경로는 글꼴 파일 .ttf가있는 경로 여야합니다.

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

Swift -Xcode 7.2에서도 Parent View Controller와 Child View Controller (Inheritance)를 사용하여 동일한 결과를 얻었습니다.

파일-신규-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()
    }
}

참고 : Parent VC에서 선언 된 Font 및 Color는 CustomFontLabel에서 구현됩니다. 장점은 Parent VC의 간단한 변경으로 uilabel / any view의 속성을 모두 함께 변경할 수 있다는 것입니다.

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)    
                }               
            }       
        }

참고 URL : https://stackoverflow.com/questions/8707082/set-a-default-font-for-whole-ios-app

반응형