Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StarPlayrX/b5e95fd455d69ae6ecabc03bc4458ba7 to your computer and use it in GitHub Desktop.
Save StarPlayrX/b5e95fd455d69ae6ecabc03bc4458ba7 to your computer and use it in GitHub Desktop.
An easy way to make code that uses UIImage cross-platform between iOS/tvOS & macOS
// Either put this in a separate file that you only include in your macOS target
// or wrap the code in #if os(macOS) / #endif
import Cocoa
// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage
// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
var cgImage: CGImage? {
var proposedRect = CGRect(origin: .zero, size: size)
return cgImage(forProposedRect: &proposedRect,
context: nil,
hints: nil)
}
convenience init?(named name: String) {
self.init(named: Name(name))
}
}
// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
let name: String
let profileImage: UIImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment