首页 > 代码库 > 属性化字符串的使用

属性化字符串的使用

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

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

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

//这个传入进来的str就是我们要展示多种颜色的文本“y = ax2 + 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;

}