UITextView linkTextAttributes font attribute not applied to NSAttributedString

后端 未结 8 641
暖寄归人
暖寄归人 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:13

    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
    
    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
提交回复
热议问题