Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewWillAppear() or other equivalent in SwiftUI

Tags:

swiftui

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?

like image 645
Ethan Halprin Avatar asked Jan 19 '26 05:01

Ethan Halprin


1 Answers

✅ 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.

like image 125
Mojtaba Hosseini Avatar answered Jan 21 '26 22:01

Mojtaba Hosseini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!