美文网首页
文字数字混合处理(数字小)

文字数字混合处理(数字小)

作者: 靠北的北 | 来源:发表于2020-08-18 17:19 被阅读0次
    // @param text 如:h2o2 co2 
    // @param size 角标数字字体size
    +(NSMutableAttributedString*)getNumberSubscriptString:(NSString*)text size:(CGFloat)size{
        if (text.length == 0) {
            return nil;
        }
        NSMutableArray *numTmpArray = [NSMutableArray array];
        NSMutableAttributedString *resAttributed = [[NSMutableAttributedString alloc]initWithString:text.uppercaseString];
        
        NSScanner *scanner = [NSScanner scannerWithString:text];
        NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
        
        while (![scanner isAtEnd]) {
            [scanner scanUpToCharactersFromSet:numbers intoString:NULL];
            int number;
            [scanner scanInt:&number];
            
            NSString *num=[NSString stringWithFormat:@"%ld",number];
            [numTmpArray addObject:num];
        }
        
        if (numTmpArray.count) {
            NSRange range = NSMakeRange(0, 0);
            for (int i = 0; i < numTmpArray.count; i++) {
                range = [text rangeOfString:numTmpArray[i]];
                [resAttributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size] range:range];
            }
        }else{
            [resAttributed addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:size] range:NSMakeRange(0, text.length)];
        }
        return resAttributed;
    }
    
    

    相关文章

      网友评论

          本文标题:文字数字混合处理(数字小)

          本文链接:https://www.haomeiwen.com/subject/hxukjktx.html