Change attributes of substrings in a NSAttributedString

二次信任 提交于 2019-11-29 22:31:00

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

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

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

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