簡體   English   中英

如何解開 SwiftUI 中的可選圖像類型列表

[英]How to unwrap an optional list of type Images in SwiftUI

我有一個全局變量var list_of_images: [Image]? 我 append 到一個按鈕點擊。 當我嘗試從另一個文件訪問它時,我會

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)

和更多。

我如何 go 關於展開可選的圖像列表?

最簡單的直接答案是使用相同的?? 您提到的提供空數組的運算符:

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不符合Identifiable

更新,基於評論:

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)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM