0

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?

c_booth
  • 2,185
  • 1
  • 13
  • 22
  • FocusedValue is to use the focused window / scene's values for something (Example: Commands (Menu), when you have multiple windows of the same app on Mac, if you want the app's **focused** window's state to be used for the menu command, so that the command takes effect only in the focused window ). Not sure I see you are doing that. You are not using any state in the view for that, also you are not updating the state. The preview is part of the same view ... so there is no point in using FocusedValue. Please read the documentation to understand the purpose of it – user1046037 Oct 12 '21 at 22:19
  • https://developer.apple.com/forums/thread/651748, Please read the workaround posted below in the thread – user1046037 Oct 12 '21 at 22:26
  • I was able to meet my goal using a different tactic: .onChange(of:perform:) together with @Environment(\.isFocused) cf https://stackoverflow.com/a/67101241/2717159. The problem was not a failure to understand what focussedValue is used for – c_booth Oct 14 '21 at 15:29

0 Answers0