我有一个水平的ScrollView,并且其中包含一个HStack。它包含多个子视图,通过ForEach渲染。我想使得当这些子视图被点击时,它们在视图中垂直居中。例如,我有以下代码:
ScrollView(.horizontal) {
HStack(alignment: .center) {
Circle() // for demonstration purposes, let's say the subviews are circles
.frame(width: 50, height: 50)
Circle()
.frame(width: 50, height: 50)
Circle()
.frame(width: 50, height: 50)
}
.frame(width: UIScreen.main.bounds.size.width, alignment: .center)
}
我尝试了这段代码:
ScrollViewReader { scrollProxy in
ScrollView(.horizontal) {
HStack(alignment: .center) {
Circle()
.frame(width: 50, height: 50)
.id("someID3")
.frame(width: 50, height: 50)
.onTapGesture {
scrollProxy.scrollTo(item.id, anchor: .center)
}
Circle()
.frame(width: 50, height: 50)
.id("someID3")
.frame(width: 50, height: 50)
.onTapGesture {
scrollProxy.scrollTo(item.id, anchor: .center)
}
...
}
}
但它似乎没有效果。有人知道如何正确地做到这一点吗?
HStack(alignment: .center)
),但是当其中任何一个被点击时,你想让它们在垂直方向上居中(VStack(alignment: .center)
)?我理解得对吗?不过我不确定你代码中的scrollTo
的作用是什么。 - Cuneyt