SwiftUI View - viewDidLoad()?

前端 未结 3 704
忘了有多久
忘了有多久 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:05

    We can achieve this using view modifier.

    1. Create ViewModifier:
    struct ViewDidLoadModifier: ViewModifier {
    
        @State private var didLoad = false
        private let action: (() -> Void)?
    
        init(perform action: (() -> Void)? = nil) {
            self.action = action
        }
    
        func body(content: Content) -> some View {
            content.onAppear {
                if didLoad == false {
                    didLoad = true
                    action?()
                }
            }
        }
    
    }
    
    1. Create View extension:
    extension View {
    
        func onLoad(perform action: (() -> Void)? = nil) -> some View {
            modifier(ViewDidLoadModifier(perform: action))
        }
    
    }
    
    1. Use like this:
    struct SomeView: View {
        var body: some View {
            VStack {
                Text("HELLO!")
            }.onLoad {
                print("onLoad")
            }
        }
    }
    

提交回复
热议问题