MarkdownKit icon indicating copy to clipboard operation
MarkdownKit copied to clipboard

Link color does not work?

Open amiantos opened this issue 6 years ago • 4 comments

Hi! I was glad to find this project, I was trying to use Down, but it's attributed string rendering leaves much to be desired. I thought this seemed like a great way to get a dark mode friendly Markdown parser into my project... and it is! So, thank you.

Unfortunately there appears to be a problem with link colors. Here's some example code...

var textColor: UIColor = .black
if #available(iOS 13.0, *) {
    textColor = .label
}
let markdownParser = MarkdownParser(font: UIFont.preferredFont(forTextStyle: .body), color: textColor)
markdownParser.link.color = textColor
return markdownParser.parse("A string [with a link](http://foo.com), and so on.")

While the main content of the string is colored properly no matter what, the link color appears to be stuck as a black color, even without the link.color call. I've tried link.color = .red as well, and no dice.

amiantos avatar Sep 11 '19 17:09 amiantos

After some surfing I found a solution, though it's outside of MarkdownKit:

var linkColor: UIColor = .darkGray
var underlineColor: UIColor = .lightGray
if #available(iOS 13.0, *) {
    linkColor = .secondaryLabel
    underlineColor = .quaternaryLabel
}
let linkAttributes: [NSAttributedString.Key: Any] = [
    NSAttributedString.Key.foregroundColor: linkColor,
    NSAttributedString.Key.underlineColor: underlineColor,
    NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
]
textView.linkTextAttributes = linkAttributes

amiantos avatar Sep 11 '19 18:09 amiantos

I think the cause is as follows.

For links, the color property is used to compute attributes - see https://github.com/bmoliveira/MarkdownKit/blob/master/MarkdownKit/Sources/Common/Protocols/MarkdownStyle.swift

However, when text is actually formatted, those attributes are not used. Instead, only the .link key of the attributed value is set. See https://github.com/bmoliveira/MarkdownKit/blob/master/MarkdownKit/Sources/Common/Elements/Link/MarkdownLink.swift#L41:

attributedString.addAttribute(NSAttributedString.Key.link, value: url, range: range)

So setting color has no effect.

phlippieb avatar May 11 '20 09:05 phlippieb

Sorry to prod but any working solution to this issue yet? @bmoliveira

iJACD avatar Jun 23 '20 22:06 iJACD

The link color attribute gets overriden by the textViews' linkTextAttributes. To use the color that you defined via the parser you must clear the linkTextAttributes like this self.textView.linkTextAttributes = [:]. You can also just alter the tintColor of your textView directly or like @amiantos showed above for a more fine grained control self.textView.linkTextAttributes.

gaebel avatar Apr 25 '21 10:04 gaebel