我有一个带有一些固定大小内容单元格的水平滚动条,我怎样才能做到这样,通过滑动即可转到下一个/上一个单元格?与 Tinder 滑动类似,但全部保留在滚动视图中。我希望单元格“点击”到 Hstack 的前缘
struct ContentView: View {
let content = ["Hello", "World", "How", "Are", "You"]
var body: some View {
ScrollView(.horizontal) {
HStack {
ForEach(content) { str in
Text(str)
.frame(width: 200, height: 200, alignment: .center)
.background(Color.green)
}
}
}
}
}
尝试将
.scrollTargetLayout()
应用于 HStack
,并将 .scrollTargetBehavior(.paging)
应用于 ScrollView
。另外:
ForEach
有错误,使用.enumerated()
是解决此问题的一种方法。.containerRelativeFrame(.horizontal)
将每个视图的宽度设置为包含的 ScrollView
的宽度。HStack
使用 spacing: 0
时效果最佳:ScrollView(.horizontal) {
HStack(spacing: 0) {
ForEach(Array(content.enumerated()), id: \.offset) { offset, str in
Text(str)
// .frame(width: 200, height: 200, alignment: .center)
.frame(height: 200, alignment: .center)
.containerRelativeFrame(.horizontal)
.background(Color.green)
.border(.black)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.paging)