首页 > 解决方案 > SwiftUI: image for Multiplatform iOS/MacOS

问题描述

Goal: SwiftUI Image on Multiplatform iOS/MacOS

Problem: when loading Image I need to wrap into an UIImage, and it won't work on macOS

Question: How can I worth with loading images that are Multiplatform?

var body: some View {

            Image(uiImage: UIImage(data: image ?? self.image)!)

    }

标签: swiftuixcode12

解决方案


Add a helper file only available to your macOS target that includes this:

typealias UIImage = NSImage

extension Image {
  init(uiImage: UIImage) {
        self.init(nsImage: uiImage)
    }
}

There are some limitations to this approach, as UIImage and NSImage don't share all the same methods and initializers, but it will work for basic cases like the one you mentioned in your question (init(data: ))

A safer version of this (if you're willing to rewrite some of your UIImage inits) might be to create a custom type eg MyImage that is aliased to NSImage on macOS and UIImage on iOS. That way you'll at least have a reminder in your code that you're not actually calling UIImage on macOS.


推荐阅读