Attributed String Foreground color not working in Swift
Asked Answered
M

11

13

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
Machismo answered 20/7, 2016 at 7:20 Comment(3)
i think String doesn't not method length, i use .characters.countUnwarrantable
There is some problem with range you are passing.Astrogate
When using correct ranges your code works ok. Check the ranges you're using.Cartel
P
13

For foregroundColor to work you need to set the .strokeWidth to negative :

let attributes : [ NSAttributedString.Key : Any ] = [.font : UIFont(name: "Helvetica", size: 11.0),
                                                             .foregroundColor : UIColor.red,
                                                             .strokeWidth : -5]
        let stringWithAttributes = NSAttributedString(string: "YOUR STRING", attributes: attributes)
Presley answered 5/9, 2019 at 6:32 Comment(1)
Wow! works like a charm. Any explanation on why -ve value works with foreground color?Marlinmarline
B
11

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.

Bowel answered 24/7, 2019 at 8:43 Comment(1)
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. Yes, this is apple bug, and still is an issue for Xcode ver 11.3.1. Setting the color from the code is fine, but setting named color from the storyboard breaks the foreground color in attributedText. Note that setting system color from the storyboard works fine (the bug appears for custom asset catalog colors).Page
F
3

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]
Fasciate answered 24/4, 2021 at 9:27 Comment(0)
G
2

On my case, its happened on ios below 13. Add negative strokeWidth will do the trick.

NSAttributedString.Key.strokeWidth: -3.0
Generality answered 16/2, 2021 at 4:16 Comment(0)
D
2

You should check your label text color. If you setup your label text color after giving attributed text value, it may overrides attributed color.

yourLabel.attributedText = attrStr //attributed string
yourLabel.textColor = UIColor.black
Dunsany answered 21/2, 2021 at 17:11 Comment(0)
J
1

April 2021, I have the same bug and nothing from the above helped me. But this helped:

Set textColor of the label to any color before you set an attributedText.

let label = UILabel()
label.textColor = .black

label.attributedText = NSAttributedString(string: "Hello, World!", attributes: [.foregroundColor: UIColor.red])
Juanajuanita answered 30/4, 2021 at 10:21 Comment(0)
H
1

This is an old question, but I just wasted a bunch of time on this same issue with the new AttributedString. Named colors do not work for AttributedString foreground color.

This does not work:

attributedString.foregroundColor = .blue

This works:

attributedString.foregroundColor = UIColor(red: 0.0, green: 0.0, blue: 1.0, alpha: 1.0)

Avoid using named colors with text color (foregroundColor) for AttributedString.

Hsu answered 30/6, 2023 at 14:24 Comment(1)
I think it does work in macOS but doesn't on iOS.Spiegelman
P
0

Reference form: NSMutableAttributedString

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()
myMutableString = NSMutableAttributedString(string: myString as 
String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
myMutableString = NSMutableAttributedString(string: myString as String, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
            myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:2))
lbl_First.attributedText = myMutableString

See Image :

enter image description here

Paramagnetic answered 20/7, 2016 at 7:23 Comment(1)
Thanks for your response, I tried that but thats not workingMachismo
D
0

I have face the same issue. Although I'm not using ranges to construct a AttributedString. So I found a weird thing that you should set the textcolor for label or textfield to clear and then set the colors through attributed string. Here is a sample code:

//Have to set the textColor to clear to make attributed string of multiple foreground colors
    termsAndConditionsLabel.textColor = .clear
    let attributedString = NSMutableAttributedString(string: "By signing up, you agree to our", attributes: [
        NSAttributedString.Key.font : UIFont(resource: .captionRegular),
        NSAttributedString.Key.foregroundColor: ThemeManager.shared.gray1
    ])
    let optionString = NSAttributedString(string: " Terms and Conditions", attributes: [
                                            NSAttributedString.Key.font: UIFont(resource: .captionRegular),
        NSAttributedString.Key.foregroundColor: ThemeManager.shared.systemBlue
    ])
    
    attributedString.append(optionString)
    
    termsAndConditionsLabel.attributedText = attributedString
Dignity answered 10/11, 2021 at 15:9 Comment(0)
M
0

for UIButton this issue solves by:

let bin = UIButton(type: .system)
btn.setTitleColor(nil, for: .normal)
Meza answered 10/2, 2022 at 13:50 Comment(0)
P
0

Was using iOS 16 simulator. My issue was that I was setting a .link value (even if it was an empty string) which made the text color always blue. Checking for nil or "" before setting the link attributed property helped

Pantin answered 12/12, 2022 at 16:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.