How do I add a custom font to a Cocoapod?

前端 未结 5 724
一生所求
一生所求 2021-01-31 03:43

I want to use a custom font within a Cocoapod, but I can\'t find anything on using a custom font within a static library. As there is no info.plist file, there is no where to te

5条回答
  •  隐瞒了意图╮
    2021-01-31 04:41

    There is a way of using a custom font without adding anything to the plist file.

        NSBundle *bundle = [NSBundle bundleForClass:[self class]];
        NSURL *fontURL = [bundle URLForResource:<#fontName#> withExtension:@"otf"/*or TTF*/];
        NSData *inData = [NSData dataWithContentsOfURL:fontURL];
        CFErrorRef error;
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)inData);
        CGFontRef font = CGFontCreateWithDataProvider(provider);
        if (!CTFontManagerRegisterGraphicsFont(font, &error)) {
            CFStringRef errorDescription = CFErrorCopyDescription(error);
            NSLog(@"Failed to load font: %@", errorDescription);
            CFRelease(errorDescription);
        }
        CFSafeRelease(font);
        CFSafeRelease(provider);
    

    You also need the CFSafeRelease function for this to work.

    void CFSafeRelease(CFTypeRef cf) {
        if (cf != NULL) {
            CFRelease(cf);
        }
    }
    

    Source: Loading iOS fonts dynamically.

    Swift equivalent:

    extension UIFont {
        static func registerFont(bundle: Bundle, fontName: String, fontExtension: String) -> Bool {
            guard let fontURL = bundle.url(forResource: fontName, withExtension: fontExtension) else {
                fatalError("Couldn't find font \(fontName)")
            }
    
            guard let fontDataProvider = CGDataProvider(url: fontURL as CFURL) else {
                fatalError("Couldn't load data from the font \(fontName)")
            }
    
            guard let font = CGFont(fontDataProvider) else {
                fatalError("Couldn't create font from data")
            }
    
            var error: Unmanaged?
            let success = CTFontManagerRegisterGraphicsFont(font, &error)
            guard success else {
                print("Error registering font: maybe it was already registered.")
                return false
            }
    
            return true
        }
    }
    

提交回复
热议问题