UITextView linkTextAttributes font attribute not applied to NSAttributedString

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

    Not sure why linkTextAttributes doesn't work for the font name. But we can achieve this by updating the link attributes of the NSAttributedString. Check the code below.

            do {
            let htmlStringCode = "For more info Click here"
    
            let string = try NSAttributedString(data: htmlStringCode.dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)
    
            let newString = NSMutableAttributedString(attributedString: string)
            string.enumerateAttributesInRange(NSRange.init(location: 0, length: string.length), options: .Reverse) { (attributes : [String : AnyObject], range:NSRange, _) -> Void in
                if let _ = attributes[NSLinkAttributeName] {
                    newString.removeAttribute(NSFontAttributeName, range: range)
                    newString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(30), range: range)
                }
            }
            textField.attributedText = newString
            textField.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.redColor(), NSUnderlineStyleAttributeName : NSUnderlineStyle.StyleNone.rawValue]
    
        }catch {
        }
    

    This is the objective-C code for this:

    NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType};
    NSData *data = [html dataUsingEncoding:NSUnicodeStringEncoding allowLossyConversion:NO];
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:data options:options documentAttributes:nil error:nil];
    NSMutableAttributedString *attributedStringWithBoldLinks = [[NSMutableAttributedString alloc] initWithAttributedString:attributedString];
    
    [attributedString enumerateAttributesInRange:NSMakeRange(0, attributedString.string.length) options:NSAttributedStringEnumerationReverse usingBlock:^(NSDictionary * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
    
        if ([attrs objectForKey:NSLinkAttributeName]) {
            [attributedStringWithBoldLinks removeAttribute:NSFontAttributeName range:range];
            [attributedStringWithBoldLinks addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"YourFont-Bold" size:16.0] range:range];
        }
    }];
    
    self.linkTextAttributes = @{NSForegroundColorAttributeName : [UIColor redColor]};
    
    self.attributedText = attributedStringWithBoldLinks;
    

提交回复
热议问题