I have an NSAttributedString
generated from HTML which includes some links. The attributed string is shown in a UITextView. I wish to apply a different font style f
For some reason postprocessing attributed string with enumerateAttributesInRange:
do not work for me.
So I used NSDataDetector
to detect link and enumerateMatchesInString:options:range:usingBlock:
to put my style for all links in string.
Here is my processing function:
+ (void) postProcessTextViewLinksStyle:(UITextView *) textView {
NSAttributedString *attributedString = textView.attributedText;
NSMutableAttributedString *attributedStringWithItalicLinks = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
NSError *error = nil;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink
error:&error];
[detector enumerateMatchesInString:[attributedString string]
options:0
range:NSMakeRange(0, [attributedString length])
usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
NSRange matchRange = [match range];
NSLog(@"Links style postprocessing. Range (from: %lu, length: %lu )", (unsigned long)matchRange.location, (unsigned long)matchRange.length);
if ([match resultType] == NSTextCheckingTypeLink) {
[attributedStringWithItalicLinks removeAttribute:NSFontAttributeName range:matchRange];
[attributedStringWithItalicLinks addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"YourFont-Italic" size:14.0f] range:matchRange];
}
}];
textView.attributedText = attributedStringWithItalicLinks;
}