具有动态范围的NSAttributedString

Mat*_*oal 0 objective-c nsattributedstring

我必须格式化一个包含3种样式的字符串.字符串类似于:

1.0000 of 2.000
Run Code Online (Sandbox Code Playgroud)

1.0000前景为红色,of字体较小,2.000必须为绿色.

问题是数字可以在任何范围内,因此第一个和第二个数字可以由4,5,6个字符组成.

如何执行这样的字符串格式化?

编辑-----------------我添加了一些信息:字符串保持其格式.例如,这可能是它的模板:N of N

Xei*_*han 5

让我们假设你有这三个:

NSString *string0 = @"1.0000"; NSString *string1 = @"of"; NSString
*string2 = @"2.000";


NSString *text = [NSString stringWithFormat:@"%@ %@ %@",
                          string0 ,string1,string2];

        //whole String attribute
        NSDictionary *attribs = @{
                                  NSForegroundColorAttributeName:[UIColor whiteColor],
                                  NSFontAttributeName:[UIFont systemFontOfSize:10]
                                  };

        NSMutableAttributedString *attributedText = [[NSMutableAttributedString alloc] initWithString:text attributes:attribs];

        NSRange string0Range = [text rangeOfString:string0];
        NSRange string1Range = [text rangeOfString:string1];
        NSRange string2Range = [text rangeOfString:string2];
        [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor redColor], NSFontAttributeName:[UIFont systemFontOfSize:15]  range:string0Range];
         [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor], NSFontAttributeName:[UIFont systemFontOfSize:12]  range:string1Range]; [attributedText setAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor], NSFontAttributeName:[UIFont systemFontOfSize:15]  range:string2Range];
        [yourLabel setAttributedText:attributedText];
Run Code Online (Sandbox Code Playgroud)