码迷,mamicode.com
首页 > 其他好文 > 详细

给UIlabel的内容中的特定字符添加颜色,可以调整大小

时间:2015-02-11 12:45:12      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:


摘要:实现对NSAttributedString的一个扩展,用法见.m的注释内容


#import <Foundation/Foundation.h>

#import <UIKit/UIKit.h>


@interface NSAttributedString (color)


+ (instancetype)getAtriWith:(NSString*)markup withDestStr:(NSArray*)deStrs andColor:(NSArray*)colors andFont:(NSArray*)fonts;


@end



#import "NSAttributedString+color.h"


@implementation NSAttributedString (color)


+ (instancetype)getAtriWith:(NSString*)markup withDestStr:(NSArray*)deStrs andColor:(NSArray*)colors andFont:(NSArray*)fonts{

    

    NSMutableAttributedString *aString = [[NSMutableAttributedString alloc] initWithString:markup];

    int count = 0;

    for (NSString* str in deStrs){

        NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:str options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];//2

        NSArray *chunks = [regex matchesInString:markup options:0 range:NSMakeRange(0, [markup length])];

        

        int subCount = 0;

        if (chunks.count > 1 && count > 0){

            subCount = count;

        }

        

        int tag = 0;

        for (NSTextCheckingResult *b in chunks) {

            [aString addAttribute:NSForegroundColorAttributeName value:colors[count] range:b.range];

            [aString addAttribute:NSFontAttributeName value:fonts[count] range:b.range];

            

            if (tag == subCount){

                break;

            }

            tag++;

        }

        count++;

    }

    

    return aString;

}


/**

  UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, 300, 0)];

 label.numberOfLines = 0;

 NSString *mark = @" 的天 小桥 流水 am id text core last 即使对方空间哈上课大家互粉阿萨德发阿萨德空间凤凰ask ";

 NSArray *destrs = @[@"",@"流水"];

 NSArray *fonts = @[[UIFont systemFontOfSize:18],[UIFont systemFontOfSize:21]];

 NSArray *colors = @[[UIColor redColor],[UIColor greenColor]];

 NSAttributedString *str = [NSAttributedString getAtriWith:mark withDestStr:destrs andColor:colors andFont:fonts];

 label.attributedText = str;

 [label sizeToFit];

 [self.view addSubview:label];

 */


@end



给UIlabel的内容中的特定字符添加颜色,可以调整大小

标签:

原文地址:http://blog.csdn.net/yakerwei/article/details/43732219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!