A source code to demo view did load behavior on SwiftUI view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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