标签上的特定字符要以红色突出显示,所以我在下面写了一个很好用的函数,但我想确认一下,还有其他有效的方法吗?例如
-(NSMutableAttributedString*)getAttributeText:(NSString*)string forSubstring:(NSString*)searchstring {
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_lblName.text];
NSRange searchRange = NSMakeRange(0,string.length);
for (NSInteger charIdx=0; charIdx<searchstring.length; charIdx++){
NSString *substring = [searchstring substringWithRange:NSMakeRange(charIdx, 1)];
NSRange foundRange;
searchRange.location = 0;
while (searchRange.location < string.length) {
searchRange.length = string.length-searchRange.location;
foundRange = [string rangeOfString:substring options:1 range:searchRange];
[text addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range:foundRange];
if (foundRange.location != NSNotFound) {
searchRange.location = foundRange.location+foundRange.length;
} else {
// no more substring to find
break;
}
}
}
return text;
}
下面是我如何使用它的代码,以及结果
NSString *string = @"James Bond Always Rocks";
_lblName.text = string;
_lblAttributedName.attributedText = [self getAttributeText:string forSubstring:@"ao"];
更新
NSString *string = @"James Bond Always Rocks";
NSRange range = [string rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"J"] options:NSCaseInsensitiveSearch];
NSLog(@"range->%@",NSStringFromRange(range)); //This prints range->{0, 1}
NSString *string = @"James Bond Always Rocks";
NSRange range = [string rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"j"] options:NSCaseInsensitiveSearch];
NSLog(@"range->%@",NSStringFromRange(range)); //This prints range->{2147483647, 0}
最佳答案
您可以通过搜索模式(在您的示例中为“[ao]+”)来简化它以消除 外循环:
NSString *string = @"James Bond Always Rocks";
NSString *searchstring = @"ao";
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
// A regular expression pattern that matches a sequence of the characters in "searchString":
NSString *pattern = [NSString stringWithFormat:@"[%@]+", [NSRegularExpression escapedPatternForString:searchstring]];
NSRange foundRange = [string rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
while (foundRange.location != NSNotFound) {
[text addAttribute: NSForegroundColorAttributeName value: [UIColor redColor] range:foundRange];
NSRange nextRange = NSMakeRange(foundRange.location + foundRange.length, string.length - foundRange.location - foundRange.length);
foundRange = [string rangeOfString:pattern options:NSRegularExpressionSearch|NSCaseInsensitiveSearch range:nextRange];
}
关于ios - 为给定字符串的所有字符突出显示字符串中的特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22400037/