UITextView linkTextAttributes font attribute not applied to NSAttributedString

后端 未结 8 751
暖寄归人
暖寄归人 2021-02-01 20:18

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

8条回答
  •  無奈伤痛
    2021-02-01 21:15

    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;
    }
    

提交回复
热议问题