swiftuiimagensattributedstringtintcolor

NSTextAttachment Tint Color


I'm trying to create a label with text, prepended with an icon, but unfortunately I'm unable to change the color of just the icon. It's always tinted with its default color.

This is how I do it:

var titleStringAttribute = NSMutableAttributedString(string: "")

var iconAttachment = NSTextAttachment(image: UIImage(systemName: "trash")!)
iconAttachment.image?.withTintColor(.red, renderingMode: .alwaysTemplate) // Does not work?!

titleStringAttribute.append(NSAttributedString(attachment: iconAttachment))

// Appending bold text to attributedText

theLabel.attributedText = titleStringAttribute

I also took a look into StackOverflow and other websites on the internet, but nothing helped yet.

I'm working with iOS 13.5.

Thanks for your answer!


Solution

  • withTintColor(_:renderingMode:) doesn't change the image you're calling it on. All it does it return a new UIImage for you to use, but you're not making use of it.

    Update your code to first create the default trash image, then create a new image from that using withTintColor, and then finally give your attachment that new image in its initializer:

    let titleStringAttribute = NSMutableAttributedString(string: "")
    
    let trashImage = UIImage(systemName: "trash")!
    let redTrashImage = trashImage.withTintColor(.red, renderingMode: .alwaysTemplate)
    let iconAttachment = NSTextAttachment(image: redTrashImage)
    
    titleStringAttribute.append(NSAttributedString(attachment: iconAttachment))
    
    // Appending bold text to attributedText
    
    theLabel.attributedText = titleStringAttribute