在视图加载后尝试加载图像,驱动视图的模型对象(请参阅下面的 MovieDetail)有一个 urlString。因为 SwiftUIView
元素没有生命周期方法(并且没有视图控制器驱动事物),所以处理这个问题的最佳方法是什么?
我遇到的主要问题是无论我尝试以哪种方式解决问题(绑定对象或使用状态变量),我的视图urlString
在加载之前都没有...
// movie object
struct Movie: Decodable, Identifiable {
let id: String
let title: String
let year: String
let type: String
var posterUrl: String
private enum CodingKeys: String, CodingKey {
case id = "imdbID"
case title = "Title"
case year = "Year"
case type = "Type"
case posterUrl = "Poster"
}
}
// root content list view that navigates to the detail view
struct ContentView : View {
var movies: [Movie]
var body: some View {
NavigationView {
List(movies) { movie in
NavigationButton(destination: MovieDetail(movie: movie)) {
MovieRow(movie: movie)
}
}
.navigationBarTitle(Text("Star Wars Movies"))
}
}
}
// detail view that needs to make the asynchronous call
struct MovieDetail : View {
let movie: Movie
@State var imageObject = BoundImageObject()
var body: some View {
HStack(alignment: .top) {
VStack {
Image(uiImage: imageObject.image)
.scaledToFit()
Text(movie.title)
.font(.subheadline)
}
}
}
}
提前致谢。