在 SwiftUI 水平滚动视图中单击单元格

问题描述 投票:0回答:1

我有一个带有一些固定大小内容单元格的水平滚动条,我怎样才能做到这样,通过滑动即可转到下一个/上一个单元格?与 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)
                    }
                }
            }
        }
    }
swift swiftui scrollview hstack
1个回答
0
投票

尝试将

.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)
© www.soinside.com 2019 - 2024. All rights reserved.