我有一个全局变量
var list_of_images: [Image]?
我在单击按钮时附加到该图像。当我尝试从另一个文件访问它时,我会这样做
ForEach(0..<list_of_images?.count) {
list_of_images?[$0]
.resizable()
.aspectRatio(contentMode: .fill)
}
但是我收到以下错误: 可选类型“Int?”的值必须解包为“Int”类型的值
我知道我需要解开 list_of_images,但我尝试了几种不起作用的方法,例如
ForEach(0..<list_of_images?.count ?? 0)
还有更多。
如何展开可选的图像列表?
最佳答案
最简单的直接答案是使用您提到的相同的 ??
运算符来提供一个空数组:
struct ContentView : View {
@State var list_of_images : [Image]? = nil
var body: some View {
ForEach(0..<(list_of_images ?? []).count) {
list_of_images?[$0]
.resizable()
.aspectRatio(contentMode: .fill)
}
}
}
但是,我通常会担心存储 Image
本身的想法。我可能会研究另一种存储对它们的引用(路径?名称?UIImages?)的方法,这些方法可以进行迭代。在这种情况下,你可以这样做:
struct ContentView : View {
@State var imageNames : [String]? = nil
var body: some View {
ForEach(imageNames ?? [], id: \.self) { imageName in
Image(imageName)
.resizable()
.aspectRatio(contentMode: .fill)
}
}
}
此方法不适用于 Image
数组,因为 Image
不符合 可识别
根据评论更新:
struct ContentView : View {
@State var images : [UIImage]? = nil
var body: some View {
ForEach(images ?? [], id: \.self) { image in
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fill)
}
}
}
关于ios - 如何在 SwiftUI 中打开图像类型的可选列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66736399/