ios 更改 NSAttributedString 中子字符串的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17486647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change attributes of substrings in a NSAttributedString
提问by mjay
This question may be a duplicate of this one. But the answers don't work for me and I want to be more specific.
这个问题可能是重复的这一个。但答案对我不起作用,我想更具体。
I have a NSString
, but I need a NS(Mutable)AttributedString
and some of the words in this string should be given a different color. I tried this:
我有一个NSString
,但我需要一个NS(Mutable)AttributedString
并且这个字符串中的一些单词应该被赋予不同的颜色。我试过这个:
NSString *text = @"This is the text and i want to replace something";
NSDictionary *attributes = @ {NSForegroundColorAttributeName : [UIColor redColor]};
NSMutableAttributedString *subString = [[NSMutableAttributedString alloc] initWithString:@"AND" attributes:attributes];
NSMutableAttributedString *newText = [[NSMutableAttributedString alloc] initWithString:text];
newText = [[newText mutableString] stringByReplacingOccurrencesOfString:@"and" withString:[subString mutableString]];
The "and" should be uppercase an red.
“and”应该是大写的红色。
The documentation says that mutableString keeps the attribute mappings. But with my replacing-thing, I have no more attributedString on the right side of the assignment (in the last line of my code-snippet).
文档说 mutableString 保留属性映射。但是随着我的替换,我在分配的右侧(在我的代码片段的最后一行)没有更多的属性字符串。
How can I get what I want? ;)
我怎样才能得到我想要的?;)
回答by Mick MacCallum
@Hyperlord's answer will work, but only if there is one occurence of the word "and" in the input string. Anyway, what I would do is use NSString's stringByReplacingOccurrencesOfString:
initially to change every "and" to an "AND", then use a little regex to detect matches in attributed string, and apply NSForegroundColorAttributeName
at that range. Here's an example:
@Hyperlord 的答案将有效,但前提是输入字符串中出现了一个单词“and”。无论如何,我会做的是stringByReplacingOccurrencesOfString:
最初使用 NSString将每个“和”更改为“与”,然后使用一点正则表达式来检测属性字符串中的匹配项,并NSForegroundColorAttributeName
在该范围内应用。下面是一个例子:
NSString *initial = @"This is the text and i want to replace something and stuff and stuff";
NSString *text = [initial stringByReplacingOccurrencesOfString:@"and" withString:@"AND"];
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:text];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(AND)" options:kNilOptions error:nil];
NSRange range = NSMakeRange(0,text.length);
[regex enumerateMatchesInString:text options:kNilOptions range:range usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange subStringRange = [result rangeAtIndex:1];
[mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:subStringRange];
}];
And finally, just apply the attributed string to your label.
最后,只需将属性字符串应用于您的标签。
[myLabel setAttributedText:mutableAttributedString];
回答by hyperlord
I think you should create a NSMutableAttributedString
using the existing NSString
and then add the style attributes with the appropriate NSRange
in order to colorize the parts you want to emphasize for example:
我认为您应该NSMutableAttributedString
使用现有创建一个NSString
,然后添加适当的样式属性,NSRange
以便为您想要强调的部分着色,例如:
NSString *text = @"This is the text and i want to replace something";
NSMutableAttributedString *mutable = [[NSMutableAttributedString alloc] initWithString:text];
[mutable addAttribute: NSForegroundColorAttributeName value:[UIColor redColor] range:[text rangeOfString:@"and"]];
Be aware: this is just from my head and not tested at all ;-)
请注意:这只是我的想法,根本没有经过测试;-)
回答by Masa S-AiYa
Please try this code in Swift 2
请在 Swift 2 中尝试此代码
var someStr = "This is the text and i want to replace something"
someStr.replaceRange(someStr.rangeOfString("and")!, with: "AND")
let attributeStr = NSMutableAttributedString(string: someStr)
attributeStr.setAttributes([NSForegroundColorAttributeName: UIColor.yellowColor()], range: NSMakeRange(17, 3) )
testLbl.attributedText = attributeStr
回答by ocwang
Here's another implementation (in Swift) that's helpful if you're doing some more complex manipulations (such as adding/deleting characters) with your attributed string:
这是另一个实现(在 Swift 中),如果您对属性字符串进行一些更复杂的操作(例如添加/删除字符),它会很有帮助:
let text = "This is the text and i want to replace something"
let mutAttrStr = NSMutableAttributedString(string: text)
let pattern = "\band\b"
let regex = NSRegularExpression(pattern: pattern, options: .allZeros, error: nil)
while let result = regex!.firstMatchInString(mutAttrStr.string, options: .allZeros, range:NSMakeRange(0, count(mutAttrStr.string)) {
let substring = NSMutableAttributedString(attributedString: mutAttrStr.attributedSubstringFromRange(result.range))
// manipulate substring attributes here
substring.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range NSMakeRange(0, count(substring.string))
mutAttrStr.replaceCharactersInRange(result.range, withAttributedString: substring)
}
Your final attributed string should be:
您的最终属性字符串应该是:
let finalAttrStr = mutAttrStr.copy() as! NSAttributedString