reference class without having to pass down to every child swiftui in swift

In SwiftUI, if multiple child views need to access a common property or method, the common approach is to pass down the reference of the class (where the common property or method is defined) from the root view to all its children through constructors. This can lead to code duplication and maintenance overhead.

However, there is a way to avoid passing references to every child view. In SwiftUI, we can use the @EnvironmentObject property wrapper to create an object that can be shared across different views.

Here's how to do it:

  1. Create a class that will hold the common data or functionality:
main.swift
final class AppData: ObservableObject {
    // Place your shared properties or functions here
}
96 chars
4 lines
  1. In your root view, create and pass the instance of this class to the environment of the view hierarchy:
main.swift
ContentView().environmentObject(AppData())
43 chars
2 lines
  1. In the child views that need access to AppData, declare a @EnvironmentObject property:
main.swift
@EnvironmentObject var appData: AppData
40 chars
2 lines
  1. Use the appData property to access the shared data or functionality:
main.swift
struct ChildView: View {
    @EnvironmentObject var appData: AppData
    
    var body: some View {
        // Use appData here
    }
}
136 chars
8 lines

Now, you can access the appData object from any child view without needing to pass it down the view hierarchy. Make sure that you only modify the appData object from the root view or a view that has access to it.

related categories

gistlibby LogSnag