Change entire application font without changing the size (Swift)

Asked

Viewed 202 times

0

Boas, I wanted to find a way to change the entire app font (Swift) into a few lines of code. Right now I have

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

and then in the Appdelegate in didFinishLaunchingWithOptions

UILabel.appearance().substituteFontName = "Roboto-Medium"

but it’s not working because of the error in Extension

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

Can anyone help me? Thank you in advance

3 answers

0

See if this works for you

extension UILabel {
    var defaultFont: UIFont {
        get { return self.font }

        set {
            guard let font  = self.font else {
                return
            }

            self.font = UIFont(name: self.defaultFont.fontName, size: font.pointSize)
        }
    }
}

UILabel.appearance().defaultFont = UIFont.init(name: "Courier-Bold", size: 25)!

0

I believe the best solution for you is to have a Singleton with your fonts and whenever you initialize a label, you ask for this Singleton which font you should use.

Or, you can use swizzling to change the default source of UILabels and UITextViews Ex: https://stackoverflow.com/a/15328022/4307080

#import <UIKit/UIKit.h>

@interface UILabel (Swizzling)

- (UIFont *)swizzledFont;

@end


#import "UILabel+Swizzling.h"
#import <objc/runtime.h>

@implementation UILabel (Swizzling)

- (UIFont *)swizzledFont
{
    return [UIFont fontWithName:@"SourceSansPro-Light" size:[[self swizzledFont] pointSize]];
}

+ (void)load
{
    Method original, swizzled;

    original = class_getInstanceMethod(self, @selector(font));
    swizzled = class_getInstanceMethod(self, @selector(swizzledFont));
    method_exchangeImplementations(original, swizzled);
}

@end

0

From swift 4 you can change the font without having to change the size.

Swift 4

  UILabel.appearance().font = UIFont.preferredFont(forTextStyle: UIFontTextStyle(rawValue: "Roboto-Medium"))

Swift 4.2

 UILabel.appearance().font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle(rawValue: "Roboto-Medium"))
  • this solution is not solving my problem, because I intend to change the source of all the Abels... which is not happening

Browser other questions tagged

You are not signed in. Login or sign up in order to post.