Search code examples
iosswiftnsattributedstring

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?


Solution

  • 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
    }