Example: this code shows how to pass @EnvironmentObject from one view to another view (and you can bypass init
)
ContentView.swift
struct ContentWrapperView: View {
@EnvironmentObject var home: HomeGlobal
var body: some View {
ContentView(home: home)
}
}
struct ContentView: View {
var home: HomeGlobal
// you can use HomeGlobal in init
init (home: HomeGlobal) {
self.home = home
}
var body: some View {
Text("\(home.defaultNavHeight)")
}
}
HomeGlobal.swift
class HomeGlobal: ObservableObject {
// Device compability
let screenSize: CGSize = UIScreen.main.bounds.size
let screenWidth: CGFloat = UIScreen.main.bounds.width
let screenHeight: CGFloat = UIScreen.main.bounds.height
private let referenceWidth: CGFloat = 375 // IPhone 8
private let referenceHeight: CGFloat = 667 // IPhone 8
var scaleFactor: CGFloat {
screenWidth / referenceWidth
}
let defaultPadding: CGFloat = 16 // IPhone 8
let defaultNavHeight: CGFloat = 44 // IPhone 8
}
App.swift
import SwiftUI
@main
struct ccApp: App {
var body: some Scene {
WindowGroup {
ContentWrapperView().environmentObject(HomeGlobal())
}
}
}