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号

  • 相关阅读:
    jquery跨域解决方案JSONP
    javascript的执行顺序
    事件委托
    JSONP解决跨域完整例子
    javascript数组&省市联动分别用js数组和JSON实现
    快速排序
    闭包
    如何解决linux的ssh连接自动断开的问题
    Django 单元测试(简单例子)
    源代码格式化工具推荐(coolformat),可以实现c,c++,c#,java,js,json,html,sql等的格式化
  • 原文地址:https://www.cnblogs.com/guatiantian/p/3698634.html
Copyright © 2011-2022 走看看