Last active
November 22, 2022 06:29
-
-
Save JohnSundell/05f837a3f901630e65e3652945424ba5 to your computer and use it in GitHub Desktop.
An easy way to make code that uses UIImage cross-platform between iOS/tvOS & macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
} |
For future visitors: removing the convenience init allows this to function as intended. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this John. Just a note, the extension init? is now giving a warning in Swift 4.2 - 'All paths through this function will call itself'. I'm not entirely sure of the change in 4.2, but since NSImage.Name is just a String alias, I can't see how this never recursed!