我正在使用 TTTAttributedLabel(https://github.com/mattt/TTTAttributedLabel)并使用它为括号中的内容设置斜体文本。问题是括号中的文本未设置为斜体。不知道我的错误在哪里..
代码如下所示:
static inline NSRegularExpression * ParenthesisRegularExpression() {
static NSRegularExpression *_parenthesisRegularExpression = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_parenthesisRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\\([^\\(\\)]+\\)" options:NSRegularExpressionCaseInsensitive error:nil];
});
return _parenthesisRegularExpression;
}
-(TTTAttributedLabel*)setItalicTextForLabel:(TTTAttributedLabel*)attributedLabel fontSize:(float)Size stringToBeSet:(NSString*)string
{
[attributedLabel setText:string afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString)
{
NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);
NSRegularExpression *regexp = ParenthesisRegularExpression();
[regexp enumerateMatchesInString:[mutableAttributedString string] options:0 range:stringRange usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
UIFont *italicSystemFont = [UIFont italicSystemFontOfSize:Size];
CTFontRef italicFont = CTFontCreateWithName((__bridge CFStringRef)italicSystemFont.fontName, italicSystemFont.pointSize, NULL);
if (italicFont) {
[mutableAttributedString removeAttribute:(NSString *)kCTFontAttributeName range:result.range];
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)italicFont range:result.range];
CFRelease(italicFont);
[mutableAttributedString removeAttribute:(NSString *)kCTForegroundColorAttributeName range:result.range];
[mutableAttributedString addAttribute:(NSString*)kCTForegroundColorAttributeName value:(id)[[UIColor grayColor] CGColor] range:result.range];
}
}];
return mutableAttributedString;
}];
return attributedLabel;
}
我这样称呼它:mylabel = [self setItalicTextForLabel:descriptionLabel fontSize:23 stringToBeSet:string];
需要一些关于我做错了什么的指导。