在UILabel中自定义NSLinkAttributeName的颜色

4

我希望能够为UILabel中的NSLinkAttributeName自定义颜色。但设置NSForegroundColorAttributeName不能影响链接文本的颜色,它仍然是蓝色。

但是NSUnderlineColorAttributeName可以运作,并且我成功地自定义了下划线颜色。有没有办法改变链接文本的颜色呢?


与苹果相关的有趣信息:https://dev59.com/N1kS5IYBdhLWcg3wY15z - Eric Aya
1个回答

3
我在尝试自定义UILabel时遇到了同样的问题,我发现NSLinkAttributeName的优先级高于NSForegroundColorAttributeName,或者说NSLinkAttributeName在前景色之后处理。

我通过遍历所有的NSLinkAttributeName并用名为CustomLinkAttribute的自定义属性替换它成功解决了这个问题。这样,它就可以正常工作了,并且我也能够通过访问我的自定义属性来获取链接。
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
}

2
哈!但是你不再有.link属性,链接将无法工作。 - Alexander Volkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接