Saturday, July 6, 2024
HomeiOS Developmentios - Go EnvironmentObject as a weak reference to SwiftUI View

ios – Go EnvironmentObject as a weak reference to SwiftUI View


So, I figured it out by wrapping the coordinator object inside an ObservableObject class and declaring a weak property inside it:

public class WeakEnvObjectWrapper<T: AnyObject>: ObservableObject {
    public unowned var weakRef: T?
    
    public init(_ weakRef: T? = nil) {
        self.weakRef = weakRef
    }
}

Utilization:

remaining public class RideCoordinator: PresentingCoordinator {

    // MARK: - Begin

    public override func begin(choices: [String : Any]? = nil) -> MSKit.CoordinatorNavigationViewController {
        _ = tremendous.begin(choices: choices)
        let welcomeView = MainScreen().environmentObject(WeakEnvObjectWrapper(self))
        startSwiftUIView(rootView: welcomeView, animated: false)
        return navigationController
    }
}

Reference inside SwiftUI Views:

struct MainScreen: View {

    // MARK: - Atmosphere

    @EnvironmentObject var coordinator: WeakEnvObjectWrapper<RideCoordinator>

    // MARK: - View

    var physique: some View {
        Button {
            coordinator.weakRef?.goToExample()
        } label: {
            Textual content("Welcome")
        }
    }
}

The code has been examined, and objects are launched accurately.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments