Skip to content

Instantly share code, notes, and snippets.

@kean
Last active Oct 7, 2021
Embed
What would you like to do?
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")
}
}
@kean
Copy link
Author

kean commented Oct 7, 2021

Screen Shot 2021-10-07 at 12 56 27 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment