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
This is a swift 3 update of answer above from @Arun Ammannaya
guard let font = UIFont.init(name: "Roboto-Regular", size: 15) else {
return
}
let newString = NSMutableAttributedString(attributedString: string)
let range = NSRange(location:0,length: string.length)
string.enumerateAttributes(in: range, options: .reverse, using: { (attributes : [String : Any], range : NSRange, _) -> Void in
if let _ = attributes[NSLinkAttributeName] {
newString.removeAttribute(NSFontAttributeName, range: range)
newString.addAttribute(NSFontAttributeName, value: font, range: range)
}
})
errorTextView.attributedText = newString
errorTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.green, NSUnderlineStyleAttributeName : NSUnderlineStyle.styleSingle.rawValue]
This is a Swift 3 solution to @CTiPKA which I prefer since it avoids HTML
guard let attributedString = errorTextView.attributedText else {
return
}
guard let font = UIFont.init(name: "Roboto-Regular", size: 15) 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(NSFontAttributeName, range: matchRange)
newString.addAttribute(NSFontAttributeName, value: font, range: matchRange)
}
})
errorTextView.attributedText = newString