自定义 UILabel 中 NSLinkAttributeName 的颜色

5 nsattributedstring ios swift

我想NSLinkAttributeName在 UILabel 中自定义颜色。但设置NSForegroundColorAttributeName不影响链接文本颜色,它仍然是蓝色。

NSUnderlineColorAttributeName有效,我能够自定义下划线颜色。是否可以以某种方式更改链接文本颜色?

Vit*_*nko 3

当我尝试自定义 UILabel 时,我也遇到了同样的问题,我认为它NSLinkAttributeNameNSForegroundColorAttributeName. 或者,也许是NSLinkAttributeName在前景色之后进行处理。

我以循环遍历所有内容结束NSLinkAttributeName,并将其替换为带有 name 的自定义属性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
}
Run Code Online (Sandbox Code Playgroud)

  • 哈!但是您不再拥有 .link 属性,并且链接将不起作用。 (2认同)