Search code examples
swiftmacosnsimagesf-symbols

Set a system image to NSImageView programatically in Swift


You can set a system image(SF Symbol) in UIKit with UIImage(systemName: "pencil"). For macOS apps you can set a system image in storyboard. However, I couldn't find a way to set a system image for macOS programatically. So is this possible, or is system images limited to storyboard only in macOS Apps.

imageView.image = NSImage(named: "pencil") //result is no image

Solution

  • The call signature is NSImage(systemSymbolName:accessibilityDescription:) (https://developer.apple.com/documentation/appkit/nsimage/3622472-init), not NSImage(named:), which tries to get an image from your app bundle -- not SF Symbols.

    Example:

    NSImage(systemSymbolName: "pencil", accessibilityDescription: nil)
    

    Note that this is only available in targeting macOS 11.0 (Big Sur) and above. Prior to this, SF Symbols were not available to Mac apps except via Catalyst.