[英]change color for single character in NSMutableAttributedString
我在NSMutableString中使用✔字符。 我想把它的颜色改成绿色。 我怎么能改变它。 我已经为它应用了颜色属性。
[String addAttribute:NSForegroundColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(107, 1)];
我已尝试使用字符串中的其他普通字符的此解决方案。 它改变了它的颜色。 但特别是这个角色不会改变颜色。 如何为此角色使用绿色
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 {
}
你可以使用✔的unicode char。
试试看,看看:
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];
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.