美文网首页
【Cocoapods】引入资源文件

【Cocoapods】引入资源文件

作者: 印比八方来 | 来源:发表于2019-02-21 19:08 被阅读0次

一.规划文件存放位置

1.创建图片文件夹及字体文件夹

文件夹

2.修改podspec文件

s.resource_bundles = {
    'LLBWordReview' => ['LLBWordReview/Images/*.*', 'LLBWordReview/Iconfonts/*.*']
}

二.使用方法

1.图片

+ (UIImage *)llbWordReviewImageNamed:(NSString *)name type:(NSString *)type {
    NSString *mainBundlePath = [NSBundle mainBundle].bundlePath;
    NSString *bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"LLBWordReview.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    if (bundle == nil) {
        bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"Frameworks/LLBWordReview.framework/LLBWordReview.bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    }
    if ([UIImage respondsToSelector:@selector(imageNamed:inBundle:compatibleWithTraitCollection:)]) {
        return [UIImage imageNamed:name inBundle:bundle compatibleWithTraitCollection:nil];
    } else {
        return [UIImage imageWithContentsOfFile:[bundle pathForResource:name ofType:type]];
    }
}

2.字体

+ (UIFont *)fontOfFileName:(NSString *)filename
                  fontName:(NSString *)fontName
                      size:(CGFloat)size {

    UIFont *font = [UIFont fontWithName:fontName size:size];
    if (!font) {
        [[self class] loadFontWithFileName:filename];
        font = [UIFont fontWithName:fontName size:size];
        if (!font) font = [UIFont systemFontOfSize:size];
    }
    return font;
}

+ (void)loadFontWithFileName:(NSString *)fileName {
    NSString *fontfileName = fileName;
    
    NSString *mainBundlePath = [NSBundle mainBundle].bundlePath;
    NSString *bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"LLBWordReview.bundle"];
    NSBundle *bundle = [NSBundle bundleWithPath:bundlePath];
    if (bundle == nil) {
        bundlePath = [NSString stringWithFormat:@"%@/%@",mainBundlePath,@"Frameworks/LLBWordReview.framework/LLBWordReview.bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath];
    }
    NSString *resourcePath = [NSString stringWithFormat:@"%@/%@",bundle.bundlePath,fontfileName];
    
    NSURL *url = [NSURL fileURLWithPath:resourcePath];
    
    NSData *fontData = [NSData dataWithContentsOfURL:url];
    if (fontData) {
        CFErrorRef error;
        CGDataProviderRef provider = CGDataProviderCreateWithCFData((CFDataRef)fontData);
        CGFontRef font = CGFontCreateWithDataProvider(provider);
        if (! CTFontManagerRegisterGraphicsFont(font, &error)) {
            CFStringRef errorDescription = CFErrorCopyDescription(error);
            NSLog(@"Failed to load font: %@", errorDescription);
            CFRelease(errorDescription);
        }
        CFRelease(font);
        CFRelease(provider);
    }
}

相关文章