问题
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
}
}
回答1:
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)
回答2:
Francesco Deliro's answer is correct, and you can avoid creating an extension to NSImage.Name with:
let logoIcon = NSImage(named: NSImage.Name("logo"))
来源:https://stackoverflow.com/questions/49052950/loading-image-from-assets-to-nsimage-keep-getting-error-expecting-nsimage-name