Are there any analogues of [NSString stringWithFormat:] for NSAttributedString

前端 未结 4 1408
后悔当初
后悔当初 2020-12-09 05:14

Usually I build app interface in interface builder. Sometimes design requires to use attributed strings (fonts, colors and etc.). It\'s easy to configure if string is static

4条回答
  •  暖寄归人
    2020-12-09 05:56

    Here's a category I wrote to add the method to NSAttributedString. You'll have to pass in NULL as the last argument to the function however, otherwise it will crash to the va_list restrictions on detecting size. [attributedString stringWithFormat:attrFormat, attrArg1, attrArg2, NULL];

    @implementation NSAttributedString(stringWithFormat)
    
    +(NSAttributedString*)stringWithFormat:(NSAttributedString*)format, ...{
        va_list args;
        va_start(args, format);
    
        NSMutableAttributedString *mutableAttributedString = (NSMutableAttributedString*)[format mutableCopy];
        NSString *mutableString = [mutableAttributedString string];
    
        while (true) {
            NSAttributedString *arg = va_arg(args, NSAttributedString*);
            if (!arg) {
                break;
            }
            NSRange rangeOfStringToBeReplaced = [mutableString rangeOfString:@"%@"];
            [mutableAttributedString replaceCharactersInRange:rangeOfStringToBeReplaced withAttributedString:arg];
        }
    
        va_end(args);
    
        return mutableAttributedString;
    }
    @end
    

提交回复
热议问题