mac-cain13 / R.swift

Strong typed, autocompleted resources like images, fonts and segues in Swift projects
MIT License
9.5k stars 764 forks source link

Cannot call value of non-function type 'ImageResource' #875

Closed xiky closed 11 months ago

xiky commented 11 months ago

I'm trying to use this repository in a new macOS project, Is it my mistake to use it?

let img = R.image.profile_default implies that img: [ImageResource]

but when i use callAsFunction, Xcode tips me an error let img = R.image.profile_default()

Cannot call value of non-function type 'ImageResource'

i'm using cocoapods

pod 'R.swift'

Is there something wrong?

xiky commented 11 months ago

Now i'm use like this NSImage(named: R.image.profile_default.name)

Please let me know if there is a better usage

tomlokhorst commented 11 months ago

That is correct.

There’s currently no better AppKit integration for images.

The only existing integrations are for SwiftUI and UIKit. See: https://github.com/mac-cain13/R.swift/blob/main/Sources/RswiftResources/Integrations/ImageResource%2BIntegrations.swift

As a workaround, you can copy-paste the UIKit callAsFunction extension in your own project, and adopt it for AppKit.

tomlokhorst commented 11 months ago

Note that if you are using Xcode 15, it also generates it’s own static resources. So there you can already do: NSImage(resource: .profile_default)

xiky commented 11 months ago

My apologies for being careless and not reading thoroughly.

Thank you very much for your response. I will close this issue.

xiky commented 11 months ago
#if os(macOS)
import AppKit
import RswiftResources.Swift

extension ImageResource {

    public var image: NSImage {
        get {
            let name = NSImage.Name(self.name)
            let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name)
            guard let result = image else {
                fatalError("Unable to load image asset named \(name).")
            }
            return result
        }
    }

    public func callAsFunction() -> NSImage? {
        let name = NSImage.Name(self.name)
        let image = (bundle == .main) ? NSImage(named: name) : bundle.image(forResource: name)
        return image
    }
}
#endif

Here is an extension, perhaps useful, where I've also added an unwrapped image.