我试图更新列表视图行的缩略图。但是swiftui在更新时拒绝更新我的图像。
getArtwork方法可以正确获取图像,但拒绝更新视图。
MusicFile是一个简单的结构体,它有一个名为art的属性,该属性的类型为Data。
struct PlaylistSongRow: View {
var musicFile: MusicFile
@State private var thumbnail: UIImage?
var body: some View {
HStack {
Group {
if let thumbnail = thumbnail {
Image(uiImage: thumbnail)
.resizable()
.scaledToFit()
.cornerRadius(5)
.frame(width: 50, height: 50)
} else {
Image(systemName: "music.note")
.resizable()
.foregroundColor(.gray)
.scaledToFit()
}
}
//not sure why this is not called.
.onChange(of: musicFile.artwork, perform: { newValue in
Task {
if let artwork = newValue {
thumbnail = await getArtwork(for: artwork)
}
}
})
VStack(alignment: .leading) {
Text(musicFile.name)
.lineLimit(1)
Text(musicFile.artist)
.font(.subheadline)
.foregroundColor(.secondary)
.lineLimit(1)
}
}
.task {
if let artwork = musicFile.artwork {
thumbnail = await getArtwork(for: artwork)
}
}
}
func getArtwork(for data: Data) async -> UIImage? {
let image = UIImage(data: data)
guard let image = image else { return nil }
let size = CGSize(width: 500, height: (500 * image.size.height) / image.size.width)
guard let thumbnail = await image.byPreparingThumbnail(ofSize: size) else { return nil }
return thumbnail
}
}
1条答案
按热度按时间u0sqgete1#
请改用
task(id:)
,例如