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
Updated for Swift 4:
let originalText = NSMutableAttributedString(attributedString: textView.attributedText)
var newString = NSMutableAttributedString(attributedString: textView.attributedText)
originalText.enumerateAttributes(in: NSRange(0..<originalText.length), options: .reverse) { (attributes, range, pointer) in
if let _ = attributes[NSAttributedString.Key.link] {
newString.removeAttribute(NSAttributedString.Key.font, range: range)
newString.addAttribute(NSAttributedString.Key.font, value: UIFont.systemFont(ofSize: 30), range: range)
}
}
self.textView.attributedText = newString // updates the text view on the vc
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;
}