foreach - 如何在 SwiftUI 列表中使用 .focusedValue
问题描述
我改编了博客文章中的一个示例,它允许我与屏幕上的另一个视图共享与 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 一起使用,为什么它不能开箱即用?
解决方案
推荐阅读
- google-tag-manager - 自定义 javascript 无法返回客户端 ID var google tag manager
- firebase - 使用 Blaze 计划时是否可以设置某种 firestore 读/写配额以避免超支?
- python - 从excel中提取文件,然后删除重复项
- mongodb - Haskell scotty Action to IO
- hibernate - 将 Hibernate 的 PersistentSet 更改为 HashSet
- python - 如何删除标签?
- c# - Unity2D 中的“OnCollisionEnter2D”出现问题
- docker - docker上的nginx:对等方重置连接
- angular - 具有第三方依赖的 kotlin 多平台
- c# - 用于替换值的内部 SIMD 指令