Change attributes of substrings in a NSAttributedString

故事扮演 提交于 2019-12-29 14:21:11

问题


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 *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.

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

How can I get what I want? ;)


回答1:


@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:

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];



回答2:


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:

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




回答3:


Please try this code in 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



回答4:


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:

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


来源:https://stackoverflow.com/questions/17486647/change-attributes-of-substrings-in-a-nsattributedstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!