如果我们要在label或者textView上显示一段文字,比如:“y = ax² + bx +c”,我们预想的结果是这样的

即让一个label或者textView上显示的文本能展示多种颜色,这时候属性化字符串就显得非常有用了。

-(NSAttributedString *)getFormulaAttributedTextWithStr:(NSString *)str

//这个传入进来的str就是我们要展示多种颜色的文本“y = ax² + bx +c”

{

    NSMutableAttributedString *attributedStr = [[NSMutableAttributedStringalloc] initWithString:str];//首先创建NSMutableAttributedString类型的串

    

    UIColor *firstColor = [colorArray objectAtIndex:0];

    UIColor *secondColor = [colorArray objectAtIndex:1];

    UIColor *thirdColor = [colorArray objectAtIndex:2];//获得要展示的颜色

    

    NSArray *array = [str componentsSeparatedByString:@" "];

 

    int length = (int)[[array objectAtIndex:0] length] + (int)[[array objectAtIndex:1] length] + 2 * 1;

    NSRange oneRange = NSMakeRange(length,[[array objectAtIndex:2] length] - 2);//获得a在字符串中的位置和长度

    int twolenth;

    NSRange twoRange = NSMakeRange(twolenth, (int)[[array objectAtIndex:4length] - 1);//获得b在字符串中的位置和长度

 

//以下三条addAttributed代码即是为指定位置的字符串添加颜色属性

    [attributedStr addAttribute:(NSString *)NSForegroundColorAttributeName

                          value:(id)firstColor.CGColor

                          range:oneRange];

    [attributedStr addAttribute:(NSString *)NSForegroundColorAttributeName

                          value:(id)secondColor.CGColor

                          range:twoRange];

    [attributedStr addAttribute:(NSString *)NSForegroundColorAttributeName

                              value:(id)thirdColor.CGColor

                             range:NSMakeRange([str length]-[[array lastObject] length],[[array lastObject] length])];

    

    return attributedStr;

}

如果要修改指定范围range的字体,如下即可

[attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(1,8)];

这样那个即把从index1开始的8个字符的字体全变成22号

posted on 2014-04-29 10:19  瓜甜甜  阅读(218)  评论(0编辑  收藏  举报