swift 为什么不调用on change来运行异步函数以更新List行视图的缩略图?

ogsagwnx  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(95)

我试图更新列表视图行的缩略图。但是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
    }
}
u0sqgete

u0sqgete1#

请改用task(id:),例如

.task(id: musicFile.artwork) {

相关问题