Xcode: Using custom fonts inside Dynamic framework

前端 未结 9 1558
再見小時候
再見小時候 2020-12-04 17:52

I added custom font to a framework. I followed all the steps, but it doesn\'t work.

I am able to set the font in Interface Builder, but when I build the project it d

9条回答
  •  不思量自难忘°
    2020-12-04 18:34

    You can load and use bundled custom fonts from your dynamic framework by implementing the +load method in your framework.

    In the load method, you locate the fonts in the bundle, then register them. This makes them available to the app, without having to specify them in the main project.

    + (void)load
    {
        static dispatch_once_t onceToken;
         dispatch_once(&onceToken, ^{
            // Dynamically load bundled custom fonts
    
            [self bible_loadFontWithName:kBIBLECustomFontBoldName];
            [self bible_loadFontWithName:kBIBLECustomFontBoldItalicName];
            [self bible_loadFontWithName:kBIBLECustomFontItalicName];
            [self bible_loadFontWithName:kBIBLECustomFontRegularName];
        });
    }
    
    + (void)bible_loadFontWithName:(NSString *)fontName
    {
         NSString *fontPath = [[NSBundle bundleForClass:[BIBLE class]] pathForResource:fontName ofType:@"otf"];
         NSData *fontData = [NSData dataWithContentsOfFile:fontPath];
    
         CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)fontData);
    
         if (provider)
         {
            CGFontRef font = CGFontCreateWithDataProvider(provider);
    
             if (font)
             {
                 CFErrorRef error = NULL;
                 if (CTFontManagerRegisterGraphicsFont(font, &error) == NO)
                 {
                     CFStringRef errorDescription = CFErrorCopyDescription(error);
                     NSLog(@"Failed to load font: %@", errorDescription);
                     CFRelease(errorDescription);
                 }
    
                 CFRelease(font);
            }
    
            CFRelease(provider);
        }
    }
    

提交回复
热议问题