• 属性化字符串的使用


    如果我们要在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号

  • 相关阅读:
    Why we should overwrite the hashCode() when we overwrite the equals()
    static dictionary methods of text compression
    xtrabackup热备主库(带gtid),实时在线还原备库
    容器提示没有这个:libaio.so.1
    ORACLE账户提示EXPIRED(GRACE)问题
    mysql批量插入测试数据
    记录一下一个脚本化修改sudo提权
    mysql从别的库dump数据下来,然后导入不同名字的其它库
    记一个mysql最简单的清理其二进制的过程
    查看当前数据库正在执行的事件
  • 原文地址:https://www.cnblogs.com/guatiantian/p/3698634.html
Copyright © 2020-2023  润新知