Change the color of a link in an NSMutableAttributedString
Swift
Updated for Swift 4.2
Use linkTextAttributes
with a UITextView
textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
And in context:
let attributedString = NSMutableAttributedString(string: "The site is www.google.com.")
let linkRange = (attributedString.string as NSString).range(of: "www.google.com")
attributedString.addAttribute(NSAttributedString.Key.link, value: "https://www.google.com", range: linkRange)
let linkAttributes: [NSAttributedString.Key : Any] = [
NSAttributedString.Key.foregroundColor: UIColor.green,
NSAttributedString.Key.underlineColor: UIColor.lightGray,
NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
// textView is a UITextView
textView.linkTextAttributes = linkAttributes
textView.attributedText = attributedString
Objective-C
Use linkTextAttributes
with a UITextView
textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor greenColor]};
Source: this answer
And from this post:
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is an example by @marcelofabri_"];
[attributedString addAttribute:NSLinkAttributeName
value:@"username://marcelofabri_"
range:[[attributedString string] rangeOfString:@"@marcelofabri_"]];
NSDictionary *linkAttributes = @{NSForegroundColorAttributeName: [UIColor greenColor],
NSUnderlineColorAttributeName: [UIColor lightGrayColor],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
// assume that textView is a UITextView previously created (either by code or Interface Builder)
textView.linkTextAttributes = linkAttributes; // customizes the appearance of links
textView.attributedText = attributedString;
textView.delegate = self;
The link color is the tint color of the label/textView. So, you can change it by changing the tint color of the view. However, this will not work if you want different link colours within the same view.