突出显示或下划线字符串中的特定单词 [英] Highlight or Underline Specific Word in a String
本文介绍了突出显示或下划线字符串中的特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 NSString
中突出显示或强调一组特定的单词.我能够检测到这些词是否存在,只是无法突出显示它们.
I would like to highlight or underline a specific set of words in a NSString
. I am able to detect if the words exist, I'm just not able to get them highlighted.
NSString * wordString = [NSString stringWithFormat:@"%@", [self.myArray componentsJoinedByString:@"\n"]];
self.myLabel.text = wordString;
if ([wordString rangeOfString:@"Base Mix"].location == NSNotFound)
{
NSLog(@"string does not contain base mix");
}
else
{
NSLog(@"string contains base mix!");
NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:wordString];
NSString * editedString = [NSString stringWithFormat:@"%lu", (unsigned long)[wordString rangeOfString:@"Base Mix"].location];
NSRange theRange = NSMakeRange(0, [editedString length]);
[string beginEditing];
[string removeAttribute:NSForegroundColorAttributeName range:theRange];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:theRange];
[string endEditing];
[self.myLabel setAttributedText:string];
}
这段代码更接近正确的路径.我确实看到了一个突出显示的字符,但它是字符串中的第一个字符,而不是我搜索过的字词.
This code is closer to the right path. I do see a highlighted character, but it's the very first character in the string and not the words that I have searched for.
推荐答案
您可以使用 NSUnderlineStyleAttributeName
和 NSUnderlineColorAttributeName
属性.我想你可以这样使用它:
You can use the NSUnderlineStyleAttributeName
and NSUnderlineColorAttributeName
attributes. I think you can use it like this:
NSRange foundRange = [wordString rangeOfString:@"Base Mix"];
if (foundRange.location != NSNotFound)
{
[wordString beginEditing];
[wordString addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInt:1] range:foundRange];
[wordString addAttribute:NSUnderlineColorAttributeName value:[NSColor redColor] range:foundRange];
[wordString endEditing];
}
这篇关于突出显示或下划线字符串中的特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文