简体   繁体   English

更改NSMutableAttributedString中单个字符的颜色

[英]change color for single character in NSMutableAttributedString

I am using ✔ character in NSMutableString. 我在NSMutableString中使用✔字符。 I want to change its color to green. 我想把它的颜色改成绿色。 how can I change it. 我怎么能改变它。 I have applied color attribute for it. 我已经为它应用了颜色属性。

[String addAttribute:NSForegroundColorAttributeName
                       value:[UIColor greenColor]
                       range:NSMakeRange(107, 1)];

I have tried this solution with the other normal character in string. 我已尝试使用字符串中的其他普通字符的此解决方案。 And its changing its color. 它改变了它的颜色。 but for particular this character its not changing the color. 但特别是这个角色不会改变颜色。 How can I use green color for this character 如何为此角色使用绿色

var myString1:NSString = "(Active)" var myString1:NSString =“(Active)”

    var myMutableString = NSMutableAttributedString()
    var str = NSString()
    str = "Name"
    myMutableString = NSMutableAttributedString(string: (str as String) + (myString1 as String), attributes: [NSFontAttributeName:UIFont(name: "Helvetica Neue", size: 18.0)!])

    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.grayColor(), range: NSRange(location:str.length, length:myString1.length))


    myMutableString.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica Neue", size: 14.0)!, range: NSRange(location: str.length,length: myString1.length))
let result = NSMutableAttributedString(string: text)
do{

    let regex = try NSRegularExpression(pattern: "✔", options: NSRegularExpression.Options(rawValue: 0))
    let range: NSRange = NSRange(location: 0, length: text.count)
    regex.enumerateMatches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) { (resultTxt, flags, stop) in
        if let subStringRange = resultTxt?.range(at:0){
            result.addAttributes([.foregroundColor :color], range: subStringRange)
        }
    }
}
catch {

}

You can use unicode char of ✔. 你可以使用✔的unicode char。

Try this and see: 试试看,看看:

NSString *testString = @"I am using \u2713 character in NSMutableString. I want to change its color to green. how can I change it. I have applied color attribute for it.";

NSString *tickmark = @"\u2713";
NSRange tickRange = [testString rangeOfString:tickmark];
NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:testString];
NSDictionary *tickAttrs = @{ NSForegroundColorAttributeName : [UIColor greenColor] };
[attributedString addAttributes:tickAttrs range:tickRange];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 120, 200, 400)];
label.font = [UIFont systemFontOfSize:20];
label.attributedText = attributedString;
label.numberOfLines = 0;
[self.view addSubview:label];

Result: 结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM