user7259578
user7259578

Reputation:

Customize color for NSLinkAttributeName in UILabel

I want to customize color for NSLinkAttributeName in UILabel. But setting NSForegroundColorAttributeName not affect link text color, it still blue.

But NSUnderlineColorAttributeName works and I was able to customize underline color. Is it possible to change link text color somehow?

Upvotes: 6

Views: 2097

Answers (1)

Vitalii Gozhenko
Vitalii Gozhenko

Reputation: 9354

I also had same issue when I tried to customize UILabel, and I figured, that NSLinkAttributeName has bigger priority than NSForegroundColorAttributeName. Or, maybe, NSLinkAttributeName processed after foreground color.

I ended with cycle through all NSLinkAttributeName and replace it with my custom attribute with name CustomLinkAttribute. After that it works like a charm. And I was also able to get link, by accessing to my custom attribute

func setupHtmlLinkTextStyle(attributedString: NSAttributedString) -> NSAttributedString {
    let updatedString = NSMutableAttributedString(attributedString: attributedString)
    attributedString.enumerateAttribute(NSLinkAttributeName,
                                        in: NSRange(location: 0, length: attributedString.length),
                                        options: [],
                                        using:
        {(attribute, range, stop) in
            if attribute != nil {
                var attributes = updatedString.attributes(at: range.location, longestEffectiveRange: nil, in: range)
                attributes[NSForegroundColorAttributeName] = UIColor.green
                attributes[NSUnderlineColorAttributeName] = UIColor.green
                attributes[NSStrokeColorAttributeName] = UIColor.green
                attributes["CustomLinkAttribute"] = attribute!
                attributes.removeValue(forKey: NSLinkAttributeName)
                updatedString.setAttributes(attributes, range: range)
            }
    })
    return updatedString
}

Upvotes: 3

Related Questions