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

我是研究僧i 提交于 2019-12-10 19:25:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!