Swift Cocoa - How to load system image "NSCaution" into NSImageView?

257 views Asked by At

I'm trying to load the system image called NSCaution programmatically. I can easily load it with Interface Builder since it's one of the displayed options for NSImageView:

nscaution system image

However, the following code does not work. It always sets img to nil:

let img = NSImage(systemSymbolName: "NSCaution", accessibilityDescription: nil)
print(img?.name())

The Apple documentation here suggests "To look up the names of system symbol images, download the SF Symbols app from Apple Design Resources." So, I downloaded that app and indeed NSCaution is not included. That's probably why the above code does not work. (Indeed, if I pick an image name like pencil that is included in the SF Symbols app, then the above code works.)

What code should I be using to load NSCaution programmatically instead of via Interface Builder? The question is broader than just NSCaution; none of the NSxxx images are loadable with the above code.

1

There are 1 answers

2
fsctl On

A comment on the original question above solved the issue. The corrected code is:

let img = NSImage(named: NSImage.cautionName)

Posting this as an answer for posterity.