在视图加载后尝试加载图像时,驱动视图的模型对象(见下面的 MovieDetail)具有 urlString。由于 SwiftUI 的 View
元素没有生命周期方法(并且没有视图控制器驱动),最好的处理方式是什么?
我遇到的主要问题是无论我尝试解决问题的方式是什么(绑定对象或使用 State 变量),我的 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)
}
}
}
}
ViewFirstAppearModifier
,以更好地传达意图和行为。 - Cristik