【发布时间】:2021-02-08 21:45:15
【问题描述】:
我是一个初级程序员所以...
在 iMac Big Sur 11.2 上使用 Xcode 12.4,该项目是“多平台应用程序”
我正在尝试构建要在网格中移动的图像数组。我将“My Image.png”复制到我的 Xcode 项目中并很好地使用它,但无论我如何尝试将它放入一个数组中,它都会返回一个 nil 数组。我在另一台电脑上试过这个,它似乎工作。 Xcode 中的哪些内容会影响这一点? (或者我只是想象它在另一台机器上工作?:-p)
代码:
@State var stringURL: URL = Bundle.main.url(forResource: "My Image", withExtension: "png")!
Image(nsImage: NSImage(byReferencing: stringURL))
@State var arrayURLs = [URL]()
arrayURLs.append(Bundle.main.url(forResource: "My Image", withExtension: "png")!)
Image(nsImage: NSImage(byReferencing: arrayURLs[0]))
前 2 行有效,但后 3 行在同一个应用程序中失败。我收到运行时错误“索引超出范围”,我认为这是因为捆绑调用返回 nil。
在上下文中基本相同。我在这个项目的最开始,从未超过第一行......
import SwiftUI
struct ContentView: View {
@State var pieceImageURLs = [URL]()
init() {
self.pieceImageURLs.append(Bundle.main.url(forResource: "Red Warrior", withExtension: "png")!)
}
var body: some View {
HStack {
Image(nsImage: NSImage(byReferencing: pieceImageURLs[0]))
}
}}
import SwiftUI
struct ContentView: View {
@State var stringURL: URL = Bundle.main.url(forResource: "My Image", withExtension: "png")!
@State var arrayURLs = [URL]()
init() {
stringURL = Bundle.main.url(forResource: "My Image", withExtension: "png")!
arrayURLs.append(Bundle.main.url(forResource: "My Image", withExtension: "png")!)
}
var body: some View {
HStack {
Image(nsImage: NSImage(byReferencing: stringURL))
Image(nsImage: NSImage(byReferencing: arrayURLs[0]))
}
Button(action: {
arrayURLs.append(Bundle.main.url(forResource: "My Image", withExtension: "png")!)
Image(nsImage: NSImage(byReferencing: arrayURLs[0]))
}) {
Text("add image")
}
}
}
'''
或者像这样一起使用数组的图像行失败
【问题讨论】:
-
您能在您的代码上下文中向我们展示吗?即,这些行在实际文件中显然不相邻存在,因为您不能声明相邻的属性和逻辑。可能有助于诊断。