Post

Replies

Boosts

Views

Activity

Get custom EnvironmentValue into PresentationDetent.Context for CustomPresentationDetent implementation.
I've tried to create an optional PresentationDetent that returns nil height based on a custom Bool EnvironmentKey I've created. It seems that no matter where I assign the environment value, the value is always set to the EnviromentKey implementation's defaultValue. This would mean that the value is simply not propagated to that function. Is this on purpose or is this a bug? On a side note, I've tried manipulating Apple provided flags (like isEnabled) and see if they are changed within the Context, the result was the same, even though I set the isEnabled flag to false, the default true was returned. Here's some sample code that reflects what I tried to accomplish: import SwiftUI struct IsLargeKey: EnvironmentKey { static let defaultValue: Bool = false } extension EnvironmentValues { var isLarge: Bool { get { self[IsLargeKey.self] } set { self[IsLargeKey.self] = newValue } } } struct SizableDetent: CustomPresentationDetent { static func height(in context: Context) -> CGFloat? { return context.isLarge ? 600 : 200 } } struct SheetContent: View { let text: String init(text: String) { self.text = text } var body: some View { Text(text) } } struct ContentView: View { @Environment(\.isLarge) private var isLarge @State private var isPresented: Bool = true @State private var detents: Set<PresentationDetent> = [.custom(SizableDetent.self)] var body: some View { // I've tried passing the environment value everywhere, nothing seems to work Text("Content") // .environment(\.isLarge, isLarge) .sheet(isPresented: $isPresented, content: { SheetContent(text: "Modal") .presentationDetents(detents) // .environment(\.isLarge, isLarge) }) } } @main struct MainApp: App { @State private var isLarge = false var body: some Scene { WindowGroup { ContentView() .environment(\.isLarge, isLarge) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 1) { isLarge = true } } } } }
1
1
191
Dec ’23