Last active
October 7, 2021 16:56
-
-
Save kean/fe8d0ffa4c8fbf2f5a558fda35ea6e6b to your computer and use it in GitHub Desktop.
This file contains 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 { | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
.commands { | |
MessageCommands() | |
} | |
} | |
} | |
struct MessageCommands: Commands { | |
private struct MenuContent: View { | |
// This _has_ to be added to the `View`, won't work if added to `Commands`! | |
@FocusedValue(\.selectedMessage) var selectedMessage | |
var body: some View { | |
Button("Print") { | |
guard let selectedMessage = selectedMessage else { return } | |
print("selected: \(selectedMessage)") | |
} | |
.keyboardShortcut("p") | |
.disabled(selectedMessage == nil) | |
} | |
} | |
var body: some Commands { | |
CommandMenu("Message") { | |
MenuContent() | |
} | |
} | |
} | |
private struct SelectedMessageKey: FocusedValueKey { | |
typealias Value = String | |
} | |
extension FocusedValues { | |
var selectedMessage: String? { | |
get { self[SelectedMessageKey.self] } | |
set { self[SelectedMessageKey.self] = newValue } | |
} | |
} | |
struct ContentView: View { | |
@State private var selectedMessage: String? = "" | |
// There are three key pieces: | |
// - Pass `selection:` in the List init | |
// - Add `tag` to list items | |
// - Add `.focusedValue` to the navigation view | |
var body: some View { | |
NavigationView { | |
List(Array(0..<10).map { $0.description }, id: \.self, selection: $selectedMessage) { message in | |
NavigationLink(destination: Text(message)) { | |
Text(message) | |
.tag(message) | |
} | |
} | |
// This doesn't work | |
//.focusedValue(\.noteValue, selectedNote!) | |
} | |
// This does | |
.focusedValue(\.selectedMessage, selectedMessage ?? "right side should never get called, I hope") | |
} | |
} |
Author
kean
commented
Oct 7, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment