forked from fermoya/SwiftUIPager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NestedExampleView.swift
89 lines (80 loc) · 2.44 KB
/
NestedExampleView.swift
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// NestedExampleView.swift
// SwiftUIPagerExample
//
// Created by Fernando Moya de Rivas on 27/05/2020.
// Copyright © 2020 Fernando Moya de Rivas. All rights reserved.
//
import SwiftUI
struct NestedExampleView: View {
@State var page: Int = 0
@State var pageOffset: Double = 0
@State var nestedPages: [Int] = [0, 0, 0, 0]
var data = Array(0..<4)
var nestedData = Array(0..<10)
var body: some View {
Pager(page: self.$page,
data: self.data,
id: \.self) { page in
self.nestedPager(page)
}
.pageOffset(pageOffset)
.swipeInteractionArea(.allAvailable)
.background(Color.gray.opacity(0.2))
}
func nestedPager(_ index: Int) -> some View {
let binding = Binding<Int>(
get: {
self.nestedPages[index]
}, set: { newValue in
var newNestedPages = self.nestedPages
newNestedPages[index] = newValue
self.nestedPages = newNestedPages
})
return VStack {
Text("Parent page: \(index)")
.font(.system(size: 22))
.bold()
.padding(20)
Spacer()
Pager(page: binding,
data: self.nestedData,
id: \.self) { page in
self.pageView(page)
}
.bounces(false)
.onDraggingBegan({
print("Dragging Began")
})
.onDraggingChanged { increment in
withAnimation {
if binding.wrappedValue == self.nestedData.count - 1, increment > 0 {
pageOffset = increment
} else if binding.wrappedValue == 0, increment < 0 {
pageOffset = increment
}
}
}
.onDraggingEnded { increment in
guard pageOffset != 0 else { return }
withAnimation {
pageOffset = 0
page += Int(increment.rounded())
}
}
.itemSpacing(10)
.itemAspectRatio(0.8, alignment: .end)
.padding(8)
}
}
func pageView(_ page: Int) -> some View {
ZStack {
Rectangle()
.fill(Color.yellow)
Text("Nested page: \(page)")
.bold()
}
.cornerRadius(5)
.shadow(radius: 5)
}
}