I want some words within my OHAttributedLabel to be links, but I want them to be colors other than blue and I don\'t want the underline.
This is giving me a blue lin
Swift 3 example for TTTAttributedLabel
:
yourLabel.linkAttributes = [
NSForegroundColorAttributeName: UIColor.green,
NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleNone.rawValue)
]
yourLabel.activeLinkAttributes = [
NSForegroundColorAttributeName: UIColor.green,
NSUnderlineStyleAttributeName: NSNumber(value: NSUnderlineStyle.styleDouble.rawValue)
]
For Swift 3 using TTTAttributedLabel
let title: NSString = "Fork me on GitHub!"
var attirutedDictionary = NSMutableDictionary(dictionary:attributedLabel.linkAttributes)
attirutedDictionary[NSForegroundColorAttributeName] = UIColor.red
attirutedDictionary[NSUnderlineStyleAttributeName] = NSNumber(value: NSUnderlineStyle.styleNone.rawValue)
attributedLabel.attributedText = NSAttributedString(string: title as String)
attributedLabel.linkAttributes = attirutedDictionary as! [AnyHashable: Any]
let range = subtitleTitle.range(of: "me")
let url = URL(string: "http://github.com/mattt/")
attributedLabel.addLink(to: url, with: range)
Swift 4.0 :
Short and simple
let LinkAttributes = NSMutableDictionary(dictionary: testLink.linkAttributes)
LinkAttributes[NSAttributedStringKey.underlineStyle] = NSNumber(value: false)
LinkAttributes[NSAttributedStringKey.foregroundColor] = UIColor.black // Whatever your label color
testLink.linkAttributes = LinkAttributes as NSDictionary as! [AnyHashable: Any]
It's better to use UITextView with "Link" feature enabled. In this case you can do it with one line:
Swift 4:
// apply link attributes to label.attributedString, then
textView.tintColor = UIColor.red // any color you want
Full example:
let attributedString = NSMutableAttributedString(string: "Here is my link")
let range = NSRange(location: 7, length:4)
attributedString.addAttribute(.link, value: "http://google.com", range: range)
attributedString.addAttribute(.underlineStyle, value: 1, range: range)
attributedString.addAttribute(.underlineColor, value: UIColor.red, range: range)
textView.tintColor = UIColor.red // any color you want
Or you can apply attributes to links only:
textView.linkTextAttributes = [
.foregroundColor: UIColor.red
.underlineStyle: 1,
.underlineColor: UIColor.red
]
If you're using a UITextView
, you might have to change the tintColor
property to change the link color.