Can I change the color of auto detected links on UITextView?
I had a UITextView that detects phone numbers and links, but this overrides my fontColor and change it to blueColor. Is there a way to format the color of auto detected links, or should I try a manual version of this function?
Instead of using an UITextView, I used an UIWebView and enabled the "auto-detect links". To change the link color, just created a regular CSS for the tag.
Appearance for UITextView is not documented, but works well.
Keep in mind UIAppearance notes:
iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window. To change the appearance of a view that’s currently in a window, remove the view from the view hierarchy and then put it back.
In other words:
Calling this code in init(), or init(coder:) methods will change UI Object appearance, but calling in loadView(), or viewDidLoad() of viewController won't.
If you want to set appearance for whole application, application(_:didFinishLaunchingWithOptions:) is good place for calling such code.
The problem with UITextView linkTextAttributes is that it applies to all automatically detected links. What if you want different links to have different attributes?
It turns out there's a trick: configure the links as part of the text view's attributed text, and set the linkTextAttributes to an empty dictionary.
Here's an example in iOS 11 / Swift 4:
// mas is the mutable attributed string we are forming...
// ... and we're going to use as the text view's `attributedText`
mas.append(NSAttributedString(string: "LINK", attributes: [
NSAttributedStringKey.link : URL(string: "https://www.apple.com")!,
NSAttributedStringKey.foregroundColor : UIColor.green,
NSAttributedStringKey.underlineStyle : NSUnderlineStyle.styleSingle.rawValue
]))
// ...
self.tv.attributedText = mas
// this is the important thing:
self.tv.linkTextAttributes = [:]