zoukankan      html  css  js  c++  java
  • 属性化字符串的使用

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

  • 相关阅读:
    apache配置虚拟主机的三种方式
    mysql ddl语句
    MySQL锁机制
    如何卸载rpm包
    RAC SCAN
    oracle rac scan ip 用途 原理
    如何用udev for asm in oracle linux 6
    ORACLE RAC NTP 时间服务器配置
    对表空间 'USERS' 无权限
    bootstrap全局css样式
  • 原文地址:https://www.cnblogs.com/guatiantian/p/3698634.html
Copyright © 2011-2022 走看看