swiftui - 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)!)
}
解决方案
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.
推荐阅读
- java - 我如何将静态类作为引用传递并在另一个类上使用它们的方法/成员?
- linux-kernel - 列出绑定到驱动程序的所有设备
- java - 如何在java中获取格式化的ldap objectSid?
- web-scraping - 在 Google 表格中使用 ImportXML
- javascript - MySQL 流和管道数据
- snowflake-cloud-data-platform - 无法解析带双引号的 JSON 对象
- r - 根据两个变量的值有条件地更改变量
- python - 如何在 Pandas DataFrame 中平滑地估算值?
- c# - Windows 会话在运行 Selenium 测试时终止
- reactjs - 如何使我的旧前端和新前端在同一个应用程序域中同时可用?