IOS 判断系统是否存在某个字体

在项目当中,如果我们用了下面这段代码设置Attribute的时候:

//通过字体设置
+(NSMutableAttributedString *)attributedChangeAllLab:(NSString *)AllStr customColor:(UIColor *)customColor andChangeStr:(NSString *)ChangeStr andChangeFont:(NSString *)font andFontSize:(CGFloat)size{
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:AllStr];
    NSRange range1 = [[str string] rangeOfString:ChangeStr];
    [str addAttribute:NSForegroundColorAttributeName value:customColor range:range1];
    if ([self isFontValueJudeName:font]) {
        //存在
        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:font size: size] range:range1];
    }else{
        [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size] range:range1];
    }
    
    return str;
}

我们需要注意:

[str addAttribute:NSFontAttributeName value:[UIFont fontWithName:font size: size] range:range1];

里面如果找不到对应的字体,就会出现APP闪退

解决方法:

在这里判断一下某个字体是否存在

+(BOOL)isFontValueJudeName:(NSString *)fontName{
    //判断字体是否存在
    BOOL  isConst = NO;
    NSArray* familys = [UIFont familyNames];
    for (int i = 0; i<[familys count]; i++) {
        NSString* family = [familys objectAtIndex:i];
        NSArray* fonts = [UIFont fontNamesForFamilyName:family];
        if ([fonts containsObject:fontName]) {
            isConst = YES;
        }
    }
    return isConst;
}

您的点赞是我分享的动力!

END.

你可能感兴趣的:(IOS 判断系统是否存在某个字体)