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
Tableview Image Content Selection Color
How to Override Internal Framework Method in Application (Outside Framework)
Performseguewithidentifier Not Working If Called from Viewdidload
Override UIgesturerecognizer Touchesbegan
Ckasset in Server Record Contains No Fileurl, Cannot Even Check for Nil
How to Use Swipe to Dismiss While Presenting a Fullscreen Modal in iOS 13
Save/Copy a File from Bundle to Desktop Using Nssavepanel
Xcode Issue: Library Not Loaded: @Rpath/Libswiftappkit.Dylib
Swift 3 Google Map Add Markers on Touch
"'Init' Is Deprecated" Warning After Swift4 Convert
Debug View Hierarchy Does Not Render UI
How to Find Realm File Location of a MAC App
How to Put View on Top of All Other Views in Swiftui
Produce Sounds of Different Frequencies in Swift
Apple Turicreate Always Return The Same Label