具有动态范围的NSAttributedString

时间:2014-01-09 18:37:44

标签: objective-c nsattributedstring

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

1.0000 of 2.000

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

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

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

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

3 个答案:

答案 0 :(得分: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];

答案 1 :(得分:3)

使用NSScanner或NSRegularExpression查找数字表达式及其各个部分。

答案 2 :(得分:1)

最简单的解决方案是:

NSString* myString = @"12.345 of 56.789";

NSMutableAttributedString * tempString = [[NSMutableAttributedString alloc] initWithString:myString];

NSRange midrange = [tempString.string rangeOfString:@"of"];



[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
                            NSForegroundColorAttributeName : [UIColor redColor]}
                    range:NSMakeRange(0, midrange.location)];

[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
                            NSForegroundColorAttributeName : [UIColor blackColor]}
                    range:midrange];

[tempString addAttributes:@{NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:16.6],
                            NSForegroundColorAttributeName : [UIColor greenColor]}
                    range:NSMakeRange(midrange.location + midrange.length, tempString.length - midrange.location - midrange.length)];

yourElement.attributedText = tempString;

enter image description here