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
}
}
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)
Francesco Deliro's answer is correct, and you can avoid creating an extension to NSImage.Name with:
let logoIcon = NSImage(named: NSImage.Name("logo"))
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"))!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With