我是 Swiftui 的新手,我很难理解如何在渲染视图时正确保留在 ObservableObject 中创建的数据?或者一个完全不同的方法来解决这个问题?
更具体地说,它是关于在 List() 的每一行中获取 HTTP 数据。
现在,它在渲染父视图时过于频繁地进行 HTTP 调用,这会导致重新加载所有行。
可以在此处找到相同的问题:在视图更新后保留视图/数据模型的参考
public class VideoFetcher: ObservableObject {
@Published var video: VideoResponse?
@Published var coverImage: UIImage?
@Published var coverImageLoading = false
@Published var categories: String?
@Published var loading = false
@Published var error = false
func load(mediaItemSlug: String = "", broadcasterSlug: String = "") {
self.loading = true
Video.findBySlug(
mediaItemSlug: mediaItemSlug,
broadcasterSlug: broadcasterSlug,
successCallback: {video -> Void in
self.video = video
self.loading = false
self.setCategories()
self.loadCoverImage()
},
errorCallback: {(error, _) -> Void in
self.loading = false
self.error = true
})
}
func loadCoverImage() {
guard self.video!.coverImageUrl != "" else {
return
}
self.coverImageLoading = true
let downloader = ImageDownloader()
let urlRequest = URLRequest(url: URL(string: self.video!.coverImageUrl)!)
let filter = AspectScaledToFillSizeFilter(size: CGSize(width: 520.0, height: 292.499999963))
downloader.download(urlRequest, filter: filter) { response in
if case .success(let image) = response.result {
self.coverImage = image
self.coverImageLoading = false
}
}
}
func setCategories() {
if (self.video!.broadcaster.categories.count > 0) {
let categoryNames = self.video!.broadcaster.categories.map { category in
return category.name == "" ? "(no name)" : category.name
}
self.categories = categoryNames.joined(separator: " • ");
}
}
}
列表()行:
struct VideoCard: View {
@ObservedObject var fetcher = VideoFetcher()
...
init() {
// Causes reload each render
self.fetcher.load()
}
var body: some View {
...
.onAppear {
// Loads that on appear but fetcher.video is nil after view re-rendered because load() wasn't called
self.fetcher.load()
}
}
}