Skip to content

Instantly share code, notes, and snippets.

@KaiOelfke
Last active February 4, 2023 03:02
Show Gist options
  • Save KaiOelfke/72f22f11beae544b555854304323bdb3 to your computer and use it in GitHub Desktop.
Save KaiOelfke/72f22f11beae544b555854304323bdb3 to your computer and use it in GitHub Desktop.
SwiftUI Updating Environment and Sheets
//
// ContentView.swift
// EnvTest
//
// Created by Kai Oelfke on 03.02.23.
//
import SwiftUI
struct Inner: View {
@Environment(\.myCustomValue) private var value
var body: some View {
Text("Inner Child: \(value)")
.transformEnvironment(\.myCustomValue, transform: { print("inner", $0) })
}
}
struct SheetView: View {
@Environment(\.myCustomValue) private var value
var body: some View {
Text("Child Sheet: \(value)")
}
}
struct ContentView: View {
@State private var showSheet = true
var body: some View {
VStack {
Inner()
Button("Show sheet") {
showSheet = true
}
.sheet(isPresented: $showSheet) {
SheetView()
.transformEnvironment(\.myCustomValue, transform: { print("sheet", $0) })
// Applying it inside makes updates available.
// .modifier(MyModifier())
//.presentationDetents([.fraction(0.1)]) // to see both values
}
}
.modifier(MyModifier())
}
}
struct MyModifier: ViewModifier {
@State var value = "Initial value from modifier"
@State var color: Color = .primary
func body(content: Content) -> some View {
content
.onAppear {
Task {
while true {
try? await Task.sleep(nanoseconds: NSEC_PER_SEC)
value = "value \((0...100).randomElement()!)"
color = [Color.blue, .red, .yellow, .orange, .green].randomElement()!
}
}
}
.myCustomValue(value)
.foregroundColor(color)
}
}
private struct MyEnvironmentKey: EnvironmentKey {
static let defaultValue: String = "Default value from Environment Key"
}
extension EnvironmentValues {
var myCustomValue: String {
get { self[MyEnvironmentKey.self] }
set { self[MyEnvironmentKey.self] = newValue }
}
}
extension View {
func myCustomValue(_ myCustomValue: String) -> some View {
environment(\.myCustomValue, myCustomValue)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment