异步加载的图像在同一视图内不可重用

Lef*_*eff 2 asynchronous image xml-parsing swiftui

我的异步图像有问题。

这是文件的链接 https://www.vadimbulavin.com/asynchronous-swiftui-image-loading-from-url-with-combine-and-swift/

底部栏的图像不会因按钮操作而改变。我该如何解决它,你能解释一下吗?

podcastIndex 是 PodcastParser 类中的 @Publisched

文字改变也没有问题,但图像始终是一样的。

这是我的内容视图:

struct ContentView: View {

@ObservedObject var podcastParser = PodcastParser()

init() {
    podcastParser.loadData()
}

var body: some View {
    NavigationView {
        List(podcastParser.podcasts.indices) { index in
            HStack {
                Button(action: {
                    podcastParser.podcastIndex = index
                    print(podcastParser.podcasts[podcastParser.podcastIndex].imageUrl)
                }) {
                    HStack {
                        AsyncImage(
                            url: podcastParser.podcasts[index].imageUrl,
                            placeholder: {
                                Text("Loading...")
                            },
                            image: { Image(uiImage: $0).resizable() }
                        )
                        .scaledToFit()
                        .frame(width: 50, height: 50)
                        Text(podcastParser.podcasts[index].name)
                    }
                }
            }
        }
    }
    VStack {
        HStack {
            AsyncImage(
                url: podcastParser.podcasts[podcastParser.podcastIndex].imageUrl,
                placeholder: {
                    Text("Loading...")
                },
                image: { Image(uiImage: $0).resizable() }
            )
            .scaledToFit()
            .frame(width: 50, height: 50)
            Text(podcastParser.podcasts[podcastParser.podcastIndex].name)
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 5

通常,当您遇到此类问题时,总是有一个强力解决方案来使用id修饰符强制视图更新。

AsyncImage(
    url: podcastParser.podcasts[podcastParser.podcastIndex].imageUrl,
    placeholder: {
        Text("Loading...")
    },
    image: { Image(uiImage: $0).resizable() }
).id(podcastParser.podcasts[podcastParser.podcastIndex].imageUrl)
Run Code Online (Sandbox Code Playgroud)

对于系统,AsyncImage这将是唯一的解决方案,但在您的情况下,您使用的是开源解决方案,因此可以修改它来解决问题。

替换StateObjectObservedObjectinAsyncImage.swift可以解决这种情况下的问题。我对这个库使用相同的方法,到目前为止还没有遇到任何问题。