本文介绍了如何从 macOS Swift 上的文档目录加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力将图像加载到 Image.我正在制作一个与 iOS 略有不同的 MacOS 应用.
I am struggling with loading an image to Image. I am making an MacOS app which is slightly different than for iOS.
我搜索了互联网,但我只找到了几个如何在 iOS 中制作它的答案.
I searched Internet however I found only several responses how to make it in iOS.
请检查代码:
import SwiftUI
struct ContentView: View {
let myUrl = URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg")
init() {
//TODO Do something with the myUrl which is valid (not nil)
}
var body: some View {
Image("turtlerock")
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
//I need to put the param to Image what I want to load an image from myUrl
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
推荐答案
首先点击你的应用目标 >签署&并删除应用沙盒,如下图所示:
First click on your app target > signing & capabilities and remove the App Sandbox as shown in the following picture:
现在您可以访问不在您的应用程序包中的文件.
Now you can access files that are not located inside your app bundle.
struct ContentView: View {
let image = NSImage(contentsOf: URL(fileURLWithPath: "/Users/codegrinder/Documents/turtlerock.jpg"))!
var body: some View {
Image(nsImage: image)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment:.center)
}
}
这篇关于如何从 macOS Swift 上的文档目录加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!