0

ForEach で選択した要素に関連付けられたデータを画面上の別のビューと共有できるようにするブログ投稿の例を採用しました。FocusedValueKey適合性を設定します。

struct FocusedNoteValue: FocusedValueKey {
    typealias Value = String
}

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

次に、ボタンを含む ForEach ビューがあり、フォーカスされたボタンは.focusedValue修飾子を使用して値を 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")
    }
}

これは ForEach では正常に機能しますが、ForEach を List に置き換えると機能しなくなります。これを List で動作させるにはどうすればよいですか? また、すぐに使用できないのはなぜですか?

4

0 に答える 0