Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- struct PagingCardView: View {
- let items: [String]
- @State private var currentIndex = 0
- var body: some View {
- GeometryReader { geometry in
- ScrollView(.horizontal, showsIndicators: false) {
- HStack(spacing: 20) {
- ForEach(0..<items.count, id: \.self) { index in
- CardView(text: items[index])
- .frame(width: geometry.size.width * 0.7) // Adjust the width as needed
- .background(GeometryReader { geo in
- Color.clear
- .preference(key: ViewOffsetKey.self, value: geo.frame(in: .global).minX)
- })
- .onPreferenceChange(ViewOffsetKey.self) { value in
- let cardWidth = geometry.size.width * 0.7
- let spacing = 20.0
- let totalWidth = cardWidth + spacing
- let offset = value - (geometry.size.width - cardWidth) / 2
- let newIndex = Int(round(offset / totalWidth))
- if newIndex != currentIndex && newIndex >= 0 && newIndex < items.count {
- currentIndex = newIndex
- }
- }
- }
- }
- .padding(.horizontal, (geometry.size.width - geometry.size.width * 0.7) / 2)
- }
- .frame(height: 200)
- .animation(.easeInOut, value: currentIndex)
- }
- }
- }
- struct CardView: View {
- let text: String
- var body: some View {
- VStack {
- Text(text)
- .font(.title)
- .padding()
- .background(Color.blue)
- .cornerRadius(10)
- .foregroundColor(.white)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Color.gray.opacity(0.2))
- .cornerRadius(10)
- .padding()
- }
- }
- struct ContentView: View {
- var body: some View {
- PagingCardView(items: ["Card 1", "Card 2", "Card 3"])
- }
- }
- @main
- struct MyApp: App {
- var body: some Scene {
- WindowGroup {
- ContentView()
- }
- }
- }
- struct ViewOffsetKey: PreferenceKey {
- typealias Value = CGFloat
- static var defaultValue: CGFloat = 0
- static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
- value = nextValue()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement