在 UILabel 中为 NSLinkAttributeName 自定义颜色
Customize color for NSLinkAttributeName in UILabel
我想在 UILabel 中为 NSLinkAttributeName
自定义颜色。但是设置 NSForegroundColorAttributeName
不影响 link 文本颜色,它仍然是蓝色。
但是 NSUnderlineColorAttributeName
有效并且我能够自定义下划线颜色。是否可以通过某种方式更改 link 文本颜色?
我在尝试自定义 UILabel 时也遇到了同样的问题,我认为 NSLinkAttributeName
的优先级高于 NSForegroundColorAttributeName
。或者,也许 NSLinkAttributeName
在前景色之后处理。
我以循环遍历所有 NSLinkAttributeName
结束,并将其替换为名称为 CustomLinkAttribute
的自定义属性。之后它就像一个魅力。通过访问我的自定义属性
,我还能够获得 link
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
}
我想在 UILabel 中为 NSLinkAttributeName
自定义颜色。但是设置 NSForegroundColorAttributeName
不影响 link 文本颜色,它仍然是蓝色。
但是 NSUnderlineColorAttributeName
有效并且我能够自定义下划线颜色。是否可以通过某种方式更改 link 文本颜色?
我在尝试自定义 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
}