I am using the following code to change the foreground color
and font
of a attribute string using Swift
. But the Font changing perfectly without any problem but the foreground color
is not changing
var checklistText = NSMutableAttributedString()
checklistText = NSMutableAttributedString(string: "\(lblChecklistName.text!),\(checklistName)")
checklistText.addAttribute(NSFontAttributeName,
value: UIFont(
name: "Helvetica",
size: 11.0)!,
range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()))
checklistText.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location: lblChecklistName.text!.length(), length: checklistName.length()+1))
lblChecklistName.attributedText = checklistText
Creating an Attributed String from MarkdownUse Markdown syntax to initialize an attributed string with text and attributes. Use a Markdown-syntax string to iniitalize an attributed string with standard or custom attributes.
A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.
I have meet the same issue. Although I'm not using ranges to construct a AttributedString
My code looked like
self.contentTextLabel.attributedText = NSAttributedString(string: "content",
attributes: [.foregroundColor: UIColor.red, .background: UIColor.blue])
When running, the background color shows blue, but the foreground color does not appear red. I thought it a swift's issue, so I also tried it in Objective-C, but still does not work.
I'm using storyboard and I resolved this by remove the named color set on that label. I think it's Apple's bug, somehow named color set on label have override foreground color set in attributed string.
Set strokeWidth to negative and strokeColor as desired color. This worked for me. It works with namedColor.
let gdprString = "test test test"
let gdprAttributes = [
NSAttributedString.Key.underlineStyle:
NSUnderlineStyle.single.rawValue,
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 15.0),
NSAttributedString.Key.link: gdprString,
NSAttributedString.Key.strokeWidth: -3.0,
NSAttributedString.Key.strokeColor: UIColor.blue
] as [NSAttributedString.Key : Any]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With