Balaji Kondalrayal
Balaji Kondalrayal

Reputation: 1751

Attributed String Foreground color not working in Swift

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

Upvotes: 13

Views: 13801

Answers (11)

mginmadison
mginmadison

Reputation: 11

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.

Upvotes: 1

kbunarjo
kbunarjo

Reputation: 1375

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

Upvotes: 0

Mike Glukhov
Mike Glukhov

Reputation: 1830

for UIButton this issue solves by:

let bin = UIButton(type: .system)
btn.setTitleColor(nil, for: .normal)

Upvotes: 0

Noman Haroon
Noman Haroon

Reputation: 193

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

Upvotes: 0

Denis Kovzan
Denis Kovzan

Reputation: 162

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])

Upvotes: 1

Aleti
Aleti

Reputation: 75

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]

Upvotes: 3

Ahrorbek Abdullayev
Ahrorbek Abdullayev

Reputation: 81

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

Upvotes: 2

darul firmansyah
darul firmansyah

Reputation: 21

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

NSAttributedString.Key.strokeWidth: -3.0

Upvotes: 2

Vadim F.
Vadim F.

Reputation: 1051

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)

Upvotes: 13

sbhhbs
sbhhbs

Reputation: 625

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.

Upvotes: 11

Kirit Modi
Kirit Modi

Reputation: 23407

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

Upvotes: 0

Related Questions