Search code examples
swiftnsimage

Loading image from Assets to NSImage keep getting error, expecting NSImage.Name


I am trying to load a file from xcassets to an NSImage, where the asset name is logo.

I tried this:

let logoIcon = NSImage(named: "logo")

But I keep getting this error:

Cannot convert value of type 'String' to expected argument type 'NSImage.Name'

I have looked into the Apple Dev Documentation and from what I can tell this is correct. But for some reason I keep getting the error.

I am trying to do it on macOS if that makes a difference

EDIT:

So I am trying to make a top menu bar app.

And I have adjust the code such that icon is loaded into logoIcon but the Icon is not set in the top menu bar.

import Cocoa

extension NSImage.Name {
    static let logo = NSImage.Name("Logo")

}


@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!
    @IBOutlet weak var statusMenu: NSMenu!

    let statusItem = NSStatusBar.system.statusItem(withLength: -1)


    func applicationDidFinishLaunching(_ aNotification: Notification) {

        // statusItem.title  = "SECRET"

        let logoIcon = NSImage(named: .logo)

        // icon?.isTemplate = true
        statusItem.image = logoIcon
        statusItem.menu = statusMenu

    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    } 

}

Solution

  • According to this answer in Apple Developer Forums:

    ... seems like NSImage(named: String) has been replaced by NSImage(named: NSImage.Name) in Swift 4.

    So as suggested in the answer you can create an extension of the struct NSImage.Name:

    extension NSImage.Name {  
        static let logo = NSImage.Name("logo")  
    } 
    

    And use it in this way:

    let logoIcon = NSImage(named: .logo)