我已经写了一个方法来突出显示一个段落中的一个单词,通过发送一个单词NSString
,它完全正常工作,直到我面对这个场景:
当我有这个文字时:
他们的母亲试图在其他地方穿上它们......
当我传递单词other
时,单词“m other
”正在突出显示,当我正在通过in
时,我得到了“衣服in
克”。
这是我的代码:
-(void)setTextHighlited :(NSString *)txt{
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.textLabel.text];
for (NSString *word in [self.textLabel.text componentsSeparatedByString:@" "]) {
if ([word hasPrefix:txt]) {
NSRange range=[self.textLabel.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
}
我尝试使用rangeOfString:options:及其所有选项,但仍然遇到同样的问题。
请咨询
答案 0 :(得分:7)
问题在于
NSRange range=[self.textLabel.text rangeOfString:word];
在文本中找到第一个出现的单词。更好的选择是 用文字枚举文本:
-(void)setTextHighlited :(NSString *)txt{
NSString *text = self.textLabel.text;
NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:text];
[text enumerateSubstringsInRange:NSMakeRange(0, [text length])
options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
if ([substring isEqualToString:txt]) {
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:substringRange];
}
}];
self.textLabel.attributedText = string;
}
这种方法有更多的优点,例如,即使它是一个单词也会找到 用引号括起来或用标点符号包围。