SwiftUI View - viewDidLoad()?

前端 未结 3 762
忘了有多久
忘了有多久 2021-01-30 10:35

Trying to load an image after the view loads, the model object driving the view (see MovieDetail below) has a urlString. Because a SwiftUI View element has no life

3条回答
  •  广开言路
    2021-01-30 11:14

    Fully updated for Xcode 11.2, Swift 5.0

    I think the viewDidLoad() just equal to implement in the body closure.
    SwiftUI gives us equivalents to UIKit’s viewDidAppear() and viewDidDisappear() in the form of onAppear() and onDisappear(). You can attach any code to these two events that you want, and SwiftUI will execute them when they occur.

    As an example, this creates two views that use onAppear() and onDisappear() to print messages, with a navigation link to move between the two:

    struct ContentView: View {
        var body: some View {
            NavigationView {
                VStack {
                    NavigationLink(destination: DetailView()) {
                        Text("Hello World")
                    }
                }
            }.onAppear {
                print("ContentView appeared!")
            }.onDisappear {
                print("ContentView disappeared!")
            }
        }
    }
    

    ref: https://www.hackingwithswift.com/quick-start/swiftui/how-to-respond-to-view-lifecycle-events-onappear-and-ondisappear

提交回复
热议问题