我要创建一个
ScrollView
,其中包含 10 个 RoundedRectangle()
,我希望它只在屏幕上显示一个矩形,但它也可以稍微查看下一个和上一个项目,以提醒用户还有其他矩形可以使用滚动。.scrollTargetLayout()
和.scrollTargetLayoutBehavior(.viewAligned)
,另外,ScrollView
中的每个项目都添加了一个.containerRelativeFrame(_:)
以确保屏幕上只会出现一个矩形,最后一个是.scrollPosition(id: )
来控制应该出现什么矩形。struct CardTheme: View {
@State private var scrollID: Int? = 0
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(0..<10, id: \.self) { i in
RoundedRectangle(cornerRadius: 25)
.frame(width: 280, height: 450)
.containerRelativeFrame(.horizontal, count: 1, spacing: 16)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.scrollPosition(id: $scrollID)
}
}
我尝试更改此代码中的计数:
.containerRelativeFrame(.horizontal, count: 1, spacing: 16)
并删除frame()
,当数字超过3时,我可以在屏幕上看到下一个项目如果你使用
containerRelativeFrame
,据我所知,你最终总是会占据整个视图。所以,我所做的是,我使用 GeometryReader
来获取 ScrollView
的大小,减去 RoundedRectangle
的宽度,将其全部除以 2,并将其值作为水平填充应用到 HStack
包裹在你的矩形周围:
struct CardTheme: View {
@State private var scrollID: Int? = 0
var body: some View {
GeometryReader { proxy in
let size = proxy.size
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(0..<10, id: \.self) { i in
RoundedRectangle(cornerRadius: 25)
.frame(width: 280, height: 450)
/// Remove this line
//.containerRelativeFrame(.horizontal, count: 1, spacing: 16)
}
}
/// 280 is the width of your item. Change it as needed.
.padding(.horizontal, (size.width - 280) / 2)
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.scrollPosition(id: $scrollID)
}
}
}
如果您想更好地自定义或控制它,您可以查看这个项目并从中获取
CoverFlowView
文件,这将创建一个可自定义的分页ScrollView
,就像您的一样,但更加灵活,因为您可以给它可以是您想要的项目之间的任何间距等,这是我在 YouTuber Kavsoft 的帮助下制作的,所以对他很信任,我也在修改版本中使用了它,并在答案中使用了一些手势here。
这是我上面发布的代码的结果:
让我知道你的想法。