Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

nsimage

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
    } 

}
like image 689
Lars Nielsen Avatar asked Mar 01 '18 15:03

Lars Nielsen


3 Answers

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)
like image 185
Francesco Deliro Avatar answered Oct 17 '22 21:10

Francesco Deliro


Francesco Deliro's answer is correct, and you can avoid creating an extension to NSImage.Name with:

let logoIcon = NSImage(named: NSImage.Name("logo"))
like image 40
jonesjones Avatar answered Oct 17 '22 19:10

jonesjones


To load from the assets catalog of the current bundle, use something like:

let image = Bundle(for: type(of: self)).image(forResource: NSImage.Name(“logo"))!

like image 1
Wil Shipley Avatar answered Oct 17 '22 21:10

Wil Shipley