Is it possible to use SF Symbols outside of UIImage?

Gene McCulley picture Gene McCulley · Oct 11, 2019 · Viewed 11.6k times · Source

I'm confused on how to use SF Symbols in text in an iOS project. I have a UIButton that uses a symbol just fine using UIImage systemImageNamed:. I would like to display a message about that button with some text in another view. I thought I should be able to use the Unicode reference to that symbol, but it doesn't render. My understanding is that these symbols are in the Private Use Area, but I cannot get them to render using code like @"Press the \U0010057C button."

I have tried importing the SFSymbolsFallback.ttf font file into my project.

I would expect to see the symbol rendered, but I get a ? instead.

Answer

Michcio picture Michcio · Oct 11, 2019

This works for me:

let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(systemName: "checkmark.circle")

// If you want to enable Color in the SF Symbols.
imageAttachment.image = UIImage(systemName: "checkmark.circle")?.withTintColor(.blue)

let fullString = NSMutableAttributedString(string: "Press the ")
fullString.append(NSAttributedString(attachment: imageAttachment))
fullString.append(NSAttributedString(string: " button"))
label.attributedText = fullString

Result:

enter image description here