更改NSAttributedString中子字符串的属性 [英] Change attributes of substrings in a NSAttributedString

查看:144
本文介绍了更改NSAttributedString中子字符串的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题可能是此问题的重复.但是答案对我不起作用,我想更具体一些.

This question may be a duplicate of this one. But the answers don't work for me and I want to be more specific.

我有一个NSString,但是我需要一个NS(Mutable)AttributedString,并且此字符串中的某些单词应使用不同的颜色.我试过了:

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

和"应大写为红色.

文档说mutableString保留属性映射.但是,有了我的替换对象,在赋值的右侧(在我的代码片段的最后一行),我就不再有attributedString了.

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

推荐答案

@Hyperlord的答案将起作用,但前提是输入字符串中出现单词"and"一次.无论如何,我要做的是首先使用NSString的stringByReplacingOccurrencesOfString:将每个"and"更改为"AND",然后使用一点正则表达式来检测属性字符串中的匹配项,并在该范围内应用NSForegroundColorAttributeName.这是一个示例:

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

这篇关于更改NSAttributedString中子字符串的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆