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
Since attributed strings are generally a pain, I find it is better to avoid the range APIs, and to keep things as immutable as possible. Set the attributes when you create the attributed string rather than going back and trying to set a range. This will also help with localization because figuring out ranges for different languages is quite tricky (the sample below does not show localization to keep things illustrative). It makes things cleaner and easier to follow. When all strings are constructed, assemble the whole thing from the pieces.
// build string
let intro = NSAttributedString(string: "I agree that I have read and understood the ")
let terms = NSAttributedString(string: "Terms and Conditions ", attributes: [.link: "https://apple.com" as Any])
let middle = NSAttributedString(string: "and ")
let privacy = NSAttributedString(string: "Privacy Policy. ", attributes: [.link: "https://example.com" as Any])
let ending = NSAttributedString(string: "This application may send me SMS messages.")
let attrStr = NSMutableAttributedString()
attrStr.append(intro)
attrStr.append(terms)
attrStr.append(middle)
attrStr.append(privacy)
attrStr.append(ending)
// set the link color
let linkAttributes: [NSAttributedString.Key: AnyObject] = [.foregroundColor: UIColor(named: "Secondary")!]
textView.linkTextAttributes = linkAttributes
textView.attributedText = attrStr