How to use .focusedValue in a SwiftUI list

858 Views Asked by At

I've adapted an example from blog post which lets me share data associated with the selected element in a ForEach with another view on the screen. It sets up the FocusedValueKey conformance:

struct FocusedNoteValue: FocusedValueKey {
    typealias Value = String
}

extension FocusedValues {
    var noteValue: FocusedNoteValue.Value? {
        get { self[FocusedNoteValue.self] }
        set { self[FocusedNoteValue.self] = newValue }
    }
}

Then it has a ForEach view with Buttons, where the focused Button uses the .focusedValue modifier to set is value to the NotePreview:

struct ContentView: View {
    var body: some View {
        Group {
            NoteEditor()
            NotePreview()
        }
    }
}

struct NoteEditor: View {
    var body: some View {
        VStack {
            ForEach((0...5), id: \.self) { num in
                let numString = "\(num)"
                Button(action: {}, label: {
                    (Text(numString))
                })
                .focusedValue(\.noteValue, numString)
            }
        }
    }
}

struct NotePreview: View {
    @FocusedValue(\.noteValue) var note

    var body: some View {
        Text(note ?? "Note is not focused")
    }
}

This works fine with the ForEach, but fails to work when the ForEach is replaced with List. How could I get this to work with List, and why is it unable to do so out of the box?

0

There are 0 best solutions below