programing

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

subpage 2023. 6. 23. 22:09
반응형

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

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

전체 앱의 기본 글꼴(기본적으로 시스템 글꼴 사용 레이블)을 설정할 수 있는 방법이 있습니까?

iOS 5에서 UIA 외관 프록시를 사용하는 것이 가능할 것 같습니다.

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

그러면 앱의 모든 UI 레이블에 대해 사용자 지정 글꼴이 원하는 대로 글꼴이 설정됩니다.각 컨트롤(UIButton, UILabel 등)에 대해 반복해야 합니다.

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

스위프트 5

Fábio Oliveira의 답변을 바탕으로 (https://stackoverflow.com/a/23042694/2082851), 나는 나만의 swift 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 {
    static var isOverrided: Bool = false

    @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, !isOverrided else { return }

        // Avoid method swizzling run twice and revert to original initialize function
        isOverrided = true

        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

이는 기본 구현을 대체하며 대부분의 UIC 컨트롤은 systemFont를 사용합니다.

Swift를 사용하는 경우 UI 레이블 확장을 만들 수 있습니다.

extension UILabel {

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

}

그런 다음 외모 프록시를 수행하는 위치:

UILabel.appearance().substituteFontName = applicationFont

다을사는동용목일표한다있니-C드습가코를 사용한 등가 .UI_APPEARANCE_SELECTOR라는이름부에라는 이름의 에.substituteFontName.

추가

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

extension UILabel {

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

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

그러면 UIA 모양 프록시의 경우:

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

참고: 굵은 글꼴 대체가 작동하지 않는 경우 기본 글꼴 이름에 "중간"이 없을 수 있습니다.필요에 따라 해당 문자열을 다른 매치로 전환합니다(아래 설명의 Mason 덕분).

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

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


주의:

  • 아래 코드는 제시된 상태에서 Apple 승인에 제출되지 않았습니다.
  • Apple 제출을 통과한 더 짧은 버전이 있습니다. 즉, 다음 버전이 없습니다.- initWithCoder: 그것이 것은 .하지만 그것이 모든 사건을 포괄하는 것은 아닙니다.
  • 다음 코드가 내 AppDelegate 클래스에 포함된 내 앱의 스타일을 설정하는 데 사용하는 클래스에 있으므로 모든 UIFont 인스턴스에서 사용할 수 있습니다.
  • 저는 변화를 훨씬 더 가시화하기 위해 여기서 Zapfino를 사용하고 있습니다.
  • 이 코드를 개선할 수 있다면 환영합니다.

이 솔루션은 최종 결과를 얻기 위해 두 가지 다른 방법을 사용합니다. 메서드를 입니다.+ systemFontWithSize:그리고 내 대안을 사용하는 것과 유사합니다(여기서는 교체가 성공적이었다는 의심을 남기지 않기 위해 "Zapfino"를 사용합니다).

다른 방법은 오버라이드입니다.- initWithCoder:한 UI를 입니다.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의 답변을 완료하기 위해 목표-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 4를 위해 저만의 타이포그래피 변환을 만들었습니다. 이 변환은 다음과 같은 대부분의 경우를 다룹니다.

첫 번째 프로젝트 구조 및 .plist 파일(같은 이름)에 글꼴 추가:

<key>UIAppFonts</key>
<array>
    <string>Typo-Light.ttf</string>
    <string>Typo-Regular.ttf</string>
    <string>Typo-Semibold.ttf</string>
    <string>Typo-LightItalic.ttf</string>
</array>

그리고나서

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

신속한 3.0 및 신속한 경고에 대한 의견

줄에서 경고 메시지를 제거할 수 있습니다.

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

다음으로 대체:

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

스위프트 5용

위의 모든 답변이 정확하지만 장치 크기에 따라 약간 다른 방식으로 답변을 했습니다.여기서 ATFontManager 클래스에서 클래스의 맨 위에 defaultFontSize로 정의된 기본 글꼴 크기를 만들었습니다. 이것은 iphoneplus의 글꼴 크기이며 필요에 따라 변경할 수 있습니다.

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의 글꼴을 관리하는 데 도움이 되는 한 가지는 Storyboard를 소스 코드로 연 다음(Files navigator > "Open as" > "Source"에서 제어 클릭 스토리보드를 연 다음 찾기 및 바꾸기를 수행하는 것입니다.

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

코드의 경우 위그스 BR이 말한 것처럼 카테고리에서 하면 문제를 해결할 수 있습니다.

닙/스토리보드의 경우, 닙/스토리보드의 UI 요소가 화면에 표시되기 전에 항상 호출하므로 Method Swizzling AwakeFromNib를 사용하여 글꼴 유형을 변경할 수 있습니다.

당신은 Aspects를 알고 있을 것입니다.Method Swizzling 기반의 AOP 프로그래밍 라이브러리입니다.UILabel의 카테고리를 만들고,UIButton,구현할 UITextView입니다.

UI 레이블:

#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

UI 텍스트 필드:

#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

UI 텍스트 보기:

#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

이상입니다. Helvetica Neue-light를 글꼴 이름으로 매크로로 변경할 수 있습니다.

아마도 그렇지 않을 것입니다. 당신은 아마도 당신의 통제 하에 글꼴을 설정할 것입니다. 그러나 당신은 예를 들어, 앱 대리인이나 다른 일반 클래스가 글꼴을 반환하는 메서드를 가지고 있고, 글꼴을 설정해야 하는 모든 것이 그 메서드를 호출할 수 있습니다.글꼴을 변경해야 할 때 도움이 됩니다. 글꼴을 설정하는 모든 곳이 아니라 한 곳에서 변경해야 합니다.다른 대안은 글꼴을 자동으로 설정하는 UI 요소의 하위 클래스를 만드는 것일 수 있지만, 이는 오버킬일 수 있습니다.

사마린을 위해서.AppDelegate 내부의 iOSFinishedLaunching()코드를 다음과 같이 입력합니다 :-

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

전체 응용프로그램에 대한 글꼴 설정 및 추가'UIAppFonts키 on Info.plist, 경로는 글꼴 파일 .ttf가 위치한 경로여야 합니다.저에게는 프로젝트의 '글꼴' 폴더 안에 있었습니다.

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

@Randall답변에서 iOS 5.0+를 언급했습니다.UIAppearance프록시를 사용하여 클래스의 모든 인스턴스 모양을 사용자 지정할 수 있습니다. 자세한 내용은 다음과 같습니다.

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

NUI는 UI 모양 프록시의 대안입니다.여러 응용프로그램에서 재사용할 수 있는 스타일시트를 수정하기만 하면 응용프로그램 전체에서 많은 UI 요소 유형의 글꼴(및 기타 많은 속성)을 제어할 수 있습니다.

NUILabel레이블을 클래스로 분류하면 스타일 시트에서 레이블의 글꼴을 쉽게 제어할 수 있습니다.

LabelFontName    String    Helvetica

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

나는 이런 종류의 글꼴 클래스를 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 )!
    }
}

Swift-Xcode 7.2에서는 부모 보기 컨트롤러와 자식 보기 컨트롤러(상속)를 사용하여 동일한 결과를 얻었습니다.

[파일] - [새로 만들기] - [코코아 터치 클래스] - [부모 보기 컨트롤러]입니다.

    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
        }

또는 사용자 정의 UI 레이블 클래스(하위 분류 방법)를 만들고 필요한 레이블을 연결합니다.

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/모든 뷰의 속성을 변경할 수 있다는 것입니다.

하위 뷰에 대해 '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

반응형