一个label 里面 显示中文和英文不同颜色

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    //这个是你请求的 东西
    NSString *stringlabel = @"hello的期望Word的期望";
    UILabel *label  = [[UILabel alloc]initWithFrame:CGRectMake(10, 70, 300, 50)];
    label.backgroundColor = [UIColor redColor];
    [self.view addSubview:label];
    //把你请求下来的数据NSString转换为 NSMutableAttributedString 这个是可以变颜色的可变string
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:stringlabel];
    //符合中文的正则表达式
    NSString *string =@"[\u4E00-\u9FA5]";
    NSError *error;
    //创建正则表达式
    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:string options:0 error:&error];
    if (!error)
    {
        //遍历字符串,获得所有的匹配字符串
        NSArray * arr = [regex matchesInString:stringlabel options:0 range:NSMakeRange(0, stringlabel.length)];
        // 遍历匹配后的每一条记录
        for (NSTextCheckingResult *match in arr) {
            NSRange range = [match range];
            NSLog(@"----%d", range);
            //遍历 拿到符合要求的 range 然后根据 range 让他改变颜色
        //http://www.cnblogs.com/taintain1984/p/3550525.html 这个是网站  你看一下
            [attStr addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(range.location, range.length)];
            //这个东西对英文 改变比较大 对中文不大你可以试试
            [attStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-ItalicMT" size:20.0] range:NSMakeRange(0, 5)];
            //然后把你的 应该用的label 的这个属性text 接受 这个可变的 String
            label.attributedText = attStr;
        }
    }
    
    
    

}

原文地址:https://www.cnblogs.com/yuejunjie/p/4682870.html