ios - 更改 NSAttributedString 中子字符串的属性

标签 ios objective-c replace nsattributedstring

这个问题可能与this one 重复.但答案对我不起作用,我想更具体一些。

我有一个 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]];

“and”应该是大写的红色。

文档说 mutableString 保留属性映射。但是随着我的替换,我在分配的右侧不再有 attributedString(在我的代码片段的最后一行)。

我怎样才能得到我想要的? ;)

最佳答案

@Hyperlord 的答案将起作用,但前提是输入字符串中出现一次“and”一词。无论如何,我要做的是使用 NSString 的 stringByReplacingOccurrencesOfString: 最初将每个“and”更改为“AND”,然后使用一点正则表达式来检测属性字符串中的匹配项,并应用 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];
}];

最后,只需将属性字符串应用到您的标签即可。

[myLabel setAttributedText:mutableAttributedString];

关于ios - 更改 NSAttributedString 中子字符串的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17486647/

相关文章:

objective-c - 将 UIPickerView 设置为 UITableview 的底部,无论滚动位置如何

iphone - 后台的 Restkit 对象映射

regex - Notepad++,搜索之间有通配符的字符串。除非(角色)出现在

html - 多个复选框图像替换 - 仅影响第一行复选框

ios - 如何旋转 "func renderer(SCNSceneRenderer, nodeFor: ARAnchor) -> SCNNode?"中的 SCNNode

ios - iOS 应用外观是否取决于部署目标?

objective-c - 在isa中存储东西

r - 当 ignore.case = TRUE 时,gsubfn 函数未提供所需的输出

ios - Fetch 从一对多关系对象中不返回任何内容

android - 手机间隙 : Android/iOS is not showing live stream video using jwplayer