Created
June 5, 2026 10:26
-
-
Save macguru/1a86c635ec663c982141a46c6f2d2bdc to your computer and use it in GitHub Desktop.
SwiftUI .focusedValue() test with sheet presentation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import SwiftUI | |
| @main | |
| struct focustestApp: App { | |
| @FocusedValue(\.color) var focusedColor: String? | |
| var body: some Scene { | |
| WindowGroup { | |
| ContentView() | |
| } | |
| .commands { | |
| CommandMenu("Color: \(focusedColor ?? "<none>")") { | |
| Button("Still \(focusedColor ?? "<none>")") {} | |
| } | |
| } | |
| } | |
| } | |
| struct ContentView: View { | |
| @State var redText: String = "Red Text here" | |
| @State var showSheet: Bool = false | |
| /// Three cases here: | |
| /// - No container works neither on macOS nor iPadOS | |
| /// - `NavigationStack` does NOT work on macOS but is fine on iPadOS | |
| /// - Only `NavigationSplitView` works on both platfroms | |
| var body: some View { | |
| // NavigationSplitView { | |
| // EmptyView() | |
| // } detail: { | |
| // NavigationStack { | |
| VStack { | |
| TextEditor(text: $redText) | |
| .foregroundStyle(.red) | |
| .focusedValue(\.color, "red") | |
| // Sheet must be defined HERE | |
| .sheet(isPresented: $showSheet) { | |
| SheetView() | |
| } | |
| Button("Show Sheet") { | |
| showSheet = true | |
| } | |
| // Sheet must NOT be defined here – will not work in ANY case | |
| // .sheet(isPresented: $showSheet) { | |
| // SheetView() | |
| // } | |
| } | |
| .padding() | |
| // Sheet must also NOT be defined here – will not work in ANY case | |
| // .sheet(isPresented: $showSheet) { | |
| // SheetView() | |
| // } | |
| } | |
| // } | |
| } | |
| struct SheetView: View { | |
| @State var greenText: String = "green Text here" | |
| @Environment(\.dismiss) var dismiss | |
| var body: some View { | |
| VStack { | |
| TextEditor(text: $greenText) | |
| .foregroundStyle(.green) | |
| .focusedValue(\.color, "green") | |
| Button("Dismiss") { | |
| dismiss() | |
| } | |
| } | |
| .padding() | |
| } | |
| } | |
| extension FocusedValues { | |
| @Entry var color: String? | |
| } | |
| #Preview { | |
| ContentView() | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This sample has:
There are two variables with two options:
Of these 3x3 = 9 combinations, the focusValue is correct only in exactly one combination:
NavigationSplitView + modifier on the TextEditor
All others either work nowhere or just on iPad (NavigationStack + modifier on the TextEditor).
Am I too dumb? Also filed as FB22941953