我有一个 SwiftUI ForEach
循环,其中包含单击时展开的 View 。类似于下面显示的 View 。
struct ExpandingView: View {
@State var isExpanded = false
var body: some View {
VStack {
Text("Hello!")
if isExpanded {
Text("World")
}
}
.onTapGesture {
withAnimation {
isExpanded.toggle()
}
}
}
}
理论上,我可以在特定位置使用 ScrollViewReader
和 scrollTo
。
ScrollViewReader { view in
ScrollView {
ForEach(0...100, id: \.self) { id in
ExpandingView()
.id(id)
.padding()
}
}
}
但是,在实践中,我不确定如何从 View 中获取 id
(因为 onTapGesture
位于 View 中)并将其向上传播一级.
另一个选项是在 ForEach
循环中使用 onTapGesture
,但我不确定如何切换 isExpanded
标志以获得正确的 View 。
最佳答案
您可以将 ScrollViewProxy
传递给行 View ,然后您现在就可以滚动了。
struct ExpandingView: View {
@State var isExpanded = false
var id: Int
var proxy: ScrollViewProxy
var body: some View {
VStack {
Text("Hello!")
if isExpanded {
Text("World")
}
}
.onTapGesture {
withAnimation {
isExpanded.toggle()
proxy.scrollTo(id, anchor: .center)
}
}
}
}
struct TestScrollView: View {
var body: some View {
ScrollViewReader { view in
ScrollView {
ForEach(0...100, id: \.self) { id in
ExpandingView(id: id, proxy: view)
.id(id)
.padding()
}
}
}
}
}
关于ios - 单击列表项时滚动到 SwiftUI 中的正确位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68142290/