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 UITextViewtextView.linkTextAttributes = linkAttributestextView.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 linkstextView.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.
Swift
let str = "By using this app you agree to our Terms and Conditions and Privacy Policy" let attributedString = NSMutableAttributedString(string: str) var foundRange = attributedString.mutableString.rangeOfString("Terms and Conditions") attributedString.addAttribute(NSLinkAttributeName, value: termsAndConditionsURL, range: foundRange) foundRange = attributedString.mutableString.rangeOfString("Privacy Policy") attributedString.addAttribute(NSLinkAttributeName, value: privacyURL, range: foundRange) policyAndTermsTextView.attributedText = attributedString policyAndTermsTextView.linkTextAttributes = [NSForegroundColorAttributeName : UIColor.blueColor()]