我有一个自定义的 UILabel。我想将我检测到的任何 URL 大写并加粗。URL 没有大写和加粗。我有一种感觉,我的检测是错误的。
这是我的正则表达式:
static NSRegularExpression *websiteRegularExpression;
static inline NSRegularExpression * WebsiteRegularExpression() {
if (!websiteRegularExpression) {
websiteRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]"
options:NSRegularExpressionCaseInsensitive
error:nil];
}
return websiteRegularExpression;
}
这是我进行解析的地方:
-(void)setBodyText
{
__block NSRegularExpression *regexp = nil;
NSString* labelText = @"http://www.google.com is a cool website";
[self.bodyLabel setText:labelText afterInheritingLabelAttributesAndConfiguringWithBlock:^NSAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);
regexp = WebsiteRegularExpression ();
NSRange nameRange = [regexp rangeOfFirstMatchInString:[mutableAttributedString string] options:0 range:stringRange];
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18.0];
CTFontRef boldFont = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (boldFont) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)boldFont range:nameRange];
CFRelease(boldFont);
}
if (nameRange.location != NSNotFound)
[mutableAttributedString replaceCharactersInRange:nameRange withString:[[[mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];
return mutableAttributedString;
}];
regexp = WebsiteRegularExpression();
NSRange linkRange = [regexp rangeOfFirstMatchInString:labelText options:0 range:NSMakeRange(0, [labelText length])];
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
[self.bodyLabel addLinkToURL:url withRange:linkRange];
}