ScrollView和UIScrollView一样可以分页

如果低于iOS 17

在View的init里面加入UIScrollView.appearance().isPagingEnabled = true就行了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
struct TestOther: View {
var body: some View {
GeometryReader { geo in
ZStack {
ScrollView(.horizontal) {

let items = [GridItem(.flexible())]

LazyHGrid(rows: items, spacing: 0, content: {
ForEach(0 ..< 10,id:\.self) { index in
(index % 2 == 0 ? Color.orange : Color.red)
.frame(width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)
}
})
.edgesIgnoringSafeArea(.all)
}
.frame(width: UIScreen.main.bounds.size.width)
.edgesIgnoringSafeArea(.all)
.ignoresSafeArea(.all)

VStack{
Text("测试一休息偶像")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.edgesIgnoringSafeArea(.all)
.ignoresSafeArea(.all)

Spacer()
}
.edgesIgnoringSafeArea(.all)
.ignoresSafeArea(.all)
}
.edgesIgnoringSafeArea(.all)
.ignoresSafeArea(.all)
}
}

init() {
UIScrollView.appearance().isPagingEnabled = true
}
}

如果iOS17+

下面的代码来自:How to make a ScrollView snap with paging or between child views

按照整个显示区域的分页滚动。

1
2
3
4
5
6
7
8
9
10
11
12
ScrollView {
ForEach(0..<50) { i in
Text("Item \(i)")
.font(.largeTitle)
.frame(maxWidth: .infinity)
.frame(height: 200)
.background(.blue)
.foregroundStyle(.white)
.clipShape(.rect(cornerRadius: 20))
}
}
.scrollTargetBehavior(.paging)

how-to-make-a-scrollview-snap-with-paging-or-between-child-views-2@2x

按照元素的分页滚动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
struct ContentView: View {
var body: some View {
ScrollView(.horizontal) {
LazyHStack {
ForEach(0..<10) { i in
RoundedRectangle(cornerRadius: 25)
.fill(Color(hue: Double(i) / 10, saturation: 1, brightness: 1).gradient)
.frame(width: 300, height: 100)
}
}
.scrollTargetLayout()
}
.scrollTargetBehavior(.viewAligned)
.safeAreaPadding(.horizontal, 40)
}
}