UITextView linkTextAttributes font attribute not applied to NSAttributedString
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 <a href=\"http://www.samplelink.com/subpage.php?id=8\">Click here</a>"
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<NSString *,id> * _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;
NSFontAttributeName not applied to NSAttributedString
I'm not sure why (probably because of having a range) but it works if you first create an NSMutableAttributedString and then you add the UIFont attributes:
extension String {
var html2AttributedString: NSMutableAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
let attrStr = try NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
attrStr.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(17.0)], range: NSRange(location: 0, length: attrStr.length))
return attrStr
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
Related Topics
How Could I Request Text from a Website in Swift
Can the Byte Order of Double Be Safely Reversed
How Is a Global Variable Set to Private Understood in Swift
Does _Arraytype or _Arrayprotocol Not Available in Swift 3.1
When Two Optionals Are Assigned to an If Let Statement, Which One Gets Unwrapped? Swift Language
Swift How to Sort Dict Keys by Byte Value and Not Alphabetically
Setting Observer for Swift Objects/Properties
Swift Tuple Has Unexpected Print Result
Getting the Time Remaining in the Time Interval of a Timer in Swift
How to Change the Order of Functions Triggered
Cannot Read Property 'Keycode' 'Character' Assertion Failure When Detect Modifier Key + Numeric Key
Why Is the Following Giving Me Zero
Generate Labels and Align in Middle
How to Use the Optional Variable in a Ternary Conditional Operator
Apple Vision Framework - Text Extraction from Image