Change color for single character in NSMutableAttributedString

I am using the βœ” character in NSMutableString. I want to change its color to green. how can i change it. I applied the color attribute for this.

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

      

I tried this solution with another normal character in the string. And its color change. but for this particular character it does not change color. How to use green for this symbol

+3


source to share


3 answers


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))

      

0


source


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 {

}

      



0


source


You can use unicode char of βœ”.

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:

enter image description here

0


source







All Articles