SwiftUI ScrollView 浏览下一个和上一个项目

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

我要创建一个

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)
    }
}

The result I want to see is like this
This is mine

我尝试更改此代码中的计数:

.containerRelativeFrame(.horizontal, count: 1, spacing: 16)
并删除
frame()
,当数字超过3时,我可以在屏幕上看到下一个项目
the preview
changed code

swiftui scrollview
1个回答
0
投票

如果你使用

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

这是我上面发布的代码的结果:

让我知道你的想法。

© www.soinside.com 2019 - 2024. All rights reserved.