I'm looking for an event in the life-cycle of a view in SwiftUI, that is equivalent to viewWillAppear(). Yes, I know there is an ".OnAppear" in SwiftUI, but that is like viewDidAppear. Is there a workaround to do get that specific execution time before view is loaded?
✅ You are looking for this modifier:
.onWillAppear { /* Your code */ }
That can be achieved by implementing this simple extension using a custom modifier:
extension View {
func onWillAppear(_ perform: @escaping () -> Void) -> some View {
modifier(WillAppearModifier(callback: perform))
}
}
struct WillAppearModifier: ViewModifier {
let callback: () -> Void
func body(content: Content) -> some View {
content.background(UIViewLifeCycleHandler(onWillAppear: callback))
}
}
And bridging the viewController lifecycle to the SwiftUI like:
struct UIViewLifeCycleHandler: UIViewControllerRepresentable {
typealias UIViewControllerType = UIViewController
var onWillAppear: () -> Void = { }
func makeUIViewController(context: UIViewControllerRepresentableContext<Self>) -> UIViewControllerType {
context.coordinator
}
func updateUIViewController(
_: UIViewControllerType,
context _: UIViewControllerRepresentableContext<Self>
) { }
func makeCoordinator() -> Self.Coordinator {
Coordinator(onWillAppear: onWillAppear)
}
class Coordinator: UIViewControllerType {
let onWillAppear: () -> Void
init(onWillAppear: @escaping () -> Void) {
self.onWillAppear = onWillAppear
super.init(nibName: nil, bundle: nil)
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
onWillAppear()
}
}
}
💡 Note that you can implement any other method you want this way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With