最佳答案
试图在视图加载后加载图像,驱动视图的模型对象(请参阅下面的 MovieDetails)具有 urlString。因为 SwiftUI View
元素没有生命周期方法(也没有视图控制器来驱动) ,那么处理这个问题的最佳方法是什么呢?
我的主要问题是,无论我尝试用哪种方式解决问题(绑定一个对象或使用状态变量) ,我的视图没有 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)
}
}
}
}
先谢谢你。