import SwiftUI
import AVKit
struct Song: Identifiable {
let id = UUID()
let title: String
let artist: String
let image: String
let mp3FileName: String
}
struct MusicView: View {
let songs: [Song] = [
Song(title: "Warriors", artist: "Imagine Dragons", image: "warriors", mp3FileName: "Warriors (ft. Imagine Dragons)"),
// other songs
]
var body: some View {
ScrollView {
VStack {
ForEach(songs) { song in
HStack {
Image(song.image) // Error here Argument type 'String' does not conform to expected type 'Decoder
.resizable()
.scaledToFit()
.frame(width: 80, height: 80)
.cornerRadius(10)
VStack(alignment: .leading) {
Text(song.title)
.font(.headline)
Text(song.artist)
.font(.subheadline)
}
Spacer()
}
.padding()
Divider()
}
}
}
}
}
我尝试过的:
我检查了资产中的图像名称与我的资产目录中的图像完全匹配。
我确认资产目录中存在这些图像。
预期行为:
我希望图像显示在歌曲标题和艺术家旁边。
错误:
Argument type 'String' does not conform to expected type 'Decoder' on Image(song.image)
我做错了什么以及如何解决它?
song.image 是您拥有的资产的完整路径吗?如果是这样,你应该先初始化 UIImage,然后将 UIImage 传递给 Image
例如
而不是
Image(song.image)
使用
Image(uiImage: UIImage(named: song.image)!)
查看 Image 和 UIImage 的文档,了解初始化每个对象的各种方法
https://developer.apple.com/documentation/swiftui/image
https://developer.apple.com/documentation/swiftui/image/init(uiimage:)
https://developer.apple.com/documentation/uikit/uiimage
https://developer.apple.com/documentation/uikit/uiimage/1624146-init