How do I add a custom font to a Cocoapod?

前端 未结 5 733
一生所求
一生所求 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:43

    For those of you finding this in 2018+, I got custom fonts to work with interface builder support (XCode 9) with these two steps:

    1. Add your fonts to the resource bundle of your framework

      s.resources = "PodName/**/*.{ttf}"
      
    2. Load fonts at runtime using Adam's answer above

      #import 
      
      void CFSafeRelease(CFTypeRef cf) { // redefine this
        if (cf != NULL) {
          CFRelease(cf);
        }
      }
      
      
      + (void) loadFonts {
        NSBundle *frameworkBundle = [NSBundle bundleForClass:self.classForCoder];
        NSURL *bundleURL = [[frameworkBundle resourceURL] URLByAppendingPathComponent:@"PodName.bundle"];
        NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
      
        NSURL *fontURL = [bundle URLForResource:@"HindMadurai-SemiBold" withExtension:@"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);
      }
      

提交回复
热议问题