我需要检测描述中给出的#TagsUILabel
并更改文本颜色,[UIColor BlueColor];
因为我无法将特定文本颜色更改UILabel
为Blue。现在我正在UILabel
习惯使用它UITableViewCell
。有什么方法可以解决此问题,以通过文本颜色区分#Tags和普通文本?有人可以帮我解决这个问题吗?
-(NSMutableAttributedString*)decorateTags:(NSString *)stringWithTags{
NSError *error = nil;
//For "Vijay #Apple Dev"
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error];
//For "Vijay @Apple Dev"
//NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"@(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];
NSInteger stringLength=[stringWithTags length];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:1];
NSString* word = [stringWithTags substringWithRange:wordRange];
//Set Font
UIFont *font=[UIFont fontWithName:@"Helvetica-Bold" size:15.0f];
[attString addAttribute:NSFontAttributeName value:font range:NSMakeRange(0, stringLength)];
//Set Background Color
UIColor *backgroundColor=[UIColor orangeColor];
[attString addAttribute:NSBackgroundColorAttributeName value:backgroundColor range:wordRange];
//Set Foreground Color
UIColor *foregroundColor=[UIColor blueColor];
[attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];
NSLog(@"Found tag %@", word);
}
// Set up your text field or label to show up the result
// yourTextField.attributedText = attString;
//
// yourLabel.attributedText = attString;
return attString;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句