SwiftUI列表未显示图像

时间:2020-07-06 23:42:41

标签: ios xcode swiftui swiftui-list

我创建了以下结构,这是我希望在SwiftUI的列表中使用的数组的简短示例:

import Foundation
import SwiftUI

struct Rune: Identifiable {
    var runeName: String
    var runeImage: String
    var runeDescription: String
    let id = UUID()
}

let runesArray = [Rune(runeName: "Fehu", runeImage: String(("Fehu.png")), runeDescription: "(Description Goes Here"),
                  Rune(runeName: "Uruz", runeImage: String(("Uruz.png")), runeDescription: "(Description Goes Here"),
                  Rune(runeName: "Thurisaz", runeImage: String(("Thurisaz.png")), runeDescription: "(Description Goes Here"]

当我使用以下代码时,我的图像没有显示,但是当我单击该行并转到我的DetailView时,我的文本runeName文本runeDescription出现了预期的样子,

ContentView:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            List(runesArray) { rune in
                NavigationLink(destination: DetailView(rune: rune)) {
                    RuneRow(rune: rune)
                }
            }
            .navigationBarTitle("Rune Companion")
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct RuneRow: View {
    
    let rune: Rune
    
    var body: some View {
        HStack {
            Image(rune.runeImage)
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 60, height: 60)
            Spacer()
            Text(rune.runeName)
                .font(.title)
                .fontWeight(.bold)
            Spacer()
        }
    }
}

DetailView:

import SwiftUI

struct DetailView: View {
    let rune: Rune
    var body: some View {
        NavigationView {
            VStack {
                Spacer()
                Image(rune.runeImage)
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .frame(width: 200, height: 200)
                Spacer()
                Text(rune.runeDescription)
                    .padding(.horizontal)
                    
                Spacer()
            }
            .navigationBarTitle(rune.runeName)
            .navigationBarTitleDisplayMode(.large)
            
        }
    }
}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(rune: runesArray[0])
    }
}

当我将Image(rune.runeImage)更改为Image("Fehu")时,Fehu的图像的确出现了,但按应做的方式填充了所有三行,表明我的图像可以成功加载。有任何想法我做错了吗?

1 个答案:

答案 0 :(得分:1)

您不需要为图像指定扩展名(.png)。

替换:

runeImage: String(("Fehu.png"))

具有:

runeImage: "Fehu"

runesArray中创建符文时。