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
Swift 5 version of Ryan Heitner's awesome answer:
guard let attributedString = textView.attributedText else { return }
guard let linkFont = UIFont(name: "HelveticaNeue-Bold", size: 20.0) else { return }
let newString = NSMutableAttributedString(attributedString: attributedString)
let types: NSTextCheckingResult.CheckingType = [.link, .phoneNumber]
guard let linkDetector = try? NSDataDetector(types: types.rawValue) else { return }
let range = NSRange(location: 0, length: attributedString.length)
linkDetector.enumerateMatches(in: attributedString.string, options: [], range: range, using: { (match: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop) in
if let matchRange = match?.range {
newString.removeAttribute(NSAttributedString.Key.font, range: matchRange)
newString.addAttribute(NSAttributedString.Key.font, value: linkFont, range: matchRange)
}
})
textView.attributedText = newString