Loading Image from Assets to Nsimage Keep Getting Error, Expecting Nsimage.Name

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

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)

Why does NSImage.Name exist?

The expectation is that you have a centralized spot where you extend NSImage.Name with static constants that define all your image names. Then, all your code references these single members, rather than repeating magic strings.

extension NSImage.Name {
static let square = NSImage.Name("square")
static let triangle = NSImage.Name("triangle")
static let circle = NSImage.Name("circle")
}

//...

let image = NSImage(named: .square)

How to load specific image from assets with Swift

You cannot load images directly with @2x or @3x, system selects appropriate image automatically, just specify the name using UIImage:

UIImage(named: "green-square-Retina")

How can I get a CGImage from my XCode assets catalog

Since OS X 10.6, NSImage has had method CGImageForProposedRect(_:context:hints:). You can pass nil for all parameters. Thus:

let nsImage = NSImage(named: "foo")
let cgImage = nsImage?.CGImageForProposedRect(nil, context: nil, hints: nil)

Change image for NSButton with Swift code

You can set the image property on NSImage like this:

myButton.image = NSImage(named: "Pressed-Button_Graphic@2x.png")

Unlike iOS it doesn't need to use setImage() method



Related Topics



Leave a reply



Submit