Skip to content

Instantly share code, notes, and snippets.

@drrost
Created January 14, 2020 16:12
Show Gist options
  • Save drrost/63a48ebf2613595dfb17c3a61094ed26 to your computer and use it in GitHub Desktop.
Save drrost/63a48ebf2613595dfb17c3a61094ed26 to your computer and use it in GitHub Desktop.
@EnvironmentObject
//
// SceneDelegate.swift
//
// Created by Rostyslav Druzhchenko on 14.01.2020.
// Copyright © 2020 Rostyslav Druzhchenko. All rights reserved.
//
// Instruction:
//
// 1. Create a sharable class:
// 1. Inherit the class from `ObservableObject`.
// 2. Create there a `property` and mark it `@Published`.
// 2. Add to environment:
// 1. Add the object as a property to `SceneDelegate` and instantiate it.
// 2. Add the object to environment
// ```let contentView = ContentView().environmentObject(transactionStore)``` in `func scene(...`.
// 3. Add to two separate views the object as a property:
// ```@EnvironmentObject var property: ClassName```
//
// Enjoy.
import UIKit
import SwiftUI
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
let textStore = TextStore()
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
let contentView = ContentView().environmentObject(textStore)
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
}
// MARK: - The environment object
class TextStore: ObservableObject {
@Published var text = "default text"
}
// MARK: - Views
struct ContentView: View {
var body: some View {
TabView {
FirstView()
.tabItem {
Image(systemName: "list.dash")
Text("First")
}
SecondView()
.tabItem {
Image(systemName: "list.dash")
Text("Second")
}
}
}
}
struct FirstView: View {
@State var label: String = ""
@EnvironmentObject var textStore: TextStore
var body: some View {
VStack {
TextField("type something", text: $label)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Button(action: action()) {
Text("Save")
}
}
}
// MARK: - Private
private func action() -> () -> Void {
{
self.textStore.text = self.label
print("Saved")
}
}
}
struct SecondView: View {
@EnvironmentObject var textStore: TextStore
var body: some View {
Text(textStore.text)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment