如何在 SwiftUI 列表中使用 .focusedValue

问题描述

我改编了 blog post 中的一个示例,它让我可以与屏幕上的另一个视图共享与 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 一起工作,为什么它不能开箱即用?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)