Skip to content

Instantly share code, notes, and snippets.

@jayesh15111988
Last active May 1, 2023 18:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jayesh15111988/7235ee6661336242bda8ce5c0ffad79b to your computer and use it in GitHub Desktop.
A source code to demo view did load behavior on SwiftUI view
import SwiftUI
struct CustomViewDidLoad: View {
var body: some View {
VStack {
Text("Hello")
}
}
}
struct CustomViewDidLoadModifier: ViewModifier {
@State private var didViewLoad = false
private let action: (() -> Void)?
init(perform action: (() -> Void)? = nil) {
self.action = action
}
func body(content: Content) -> some View {
content.onAppear {
if !didViewLoad {
didViewLoad = true
action?()
}
}
}
}
extension View {
func onLoad(perform action: (() -> Void)? = nil) -> some View {
modifier(CustomViewDidLoadModifier(perform: action))
}
}
struct CustomViewDidLoad_Previews: PreviewProvider {
static var previews: some View {
CustomViewDidLoad().onLoad {
print("YES")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment