Advertisement
Milotronik

card2

Aug 8th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.60 KB | None | 0 0
  1. import SwiftUI
  2.  
  3. struct PagingCardView: View {
  4. let items: [String]
  5. @State private var currentIndex = 0
  6.  
  7. var body: some View {
  8. GeometryReader { geometry in
  9. ScrollView(.horizontal, showsIndicators: false) {
  10. HStack(spacing: 20) {
  11. ForEach(0..<items.count, id: \.self) { index in
  12. CardView(text: items[index])
  13. .frame(width: geometry.size.width * 0.7) // Adjust the width as needed
  14. .background(GeometryReader { geo in
  15. Color.clear
  16. .preference(key: ViewOffsetKey.self, value: geo.frame(in: .global).minX)
  17. })
  18. .onPreferenceChange(ViewOffsetKey.self) { value in
  19. let cardWidth = geometry.size.width * 0.7
  20. let spacing = 20.0
  21. let totalWidth = cardWidth + spacing
  22. let offset = value - (geometry.size.width - cardWidth) / 2
  23. let newIndex = Int(round(offset / totalWidth))
  24. if newIndex != currentIndex && newIndex >= 0 && newIndex < items.count {
  25. currentIndex = newIndex
  26. }
  27. }
  28. }
  29. }
  30. .padding(.horizontal, (geometry.size.width - geometry.size.width * 0.7) / 2)
  31. }
  32. .frame(height: 200)
  33. .animation(.easeInOut, value: currentIndex)
  34. }
  35. }
  36. }
  37.  
  38. struct CardView: View {
  39. let text: String
  40.  
  41. var body: some View {
  42. VStack {
  43. Text(text)
  44. .font(.title)
  45. .padding()
  46. .background(Color.blue)
  47. .cornerRadius(10)
  48. .foregroundColor(.white)
  49. }
  50. .frame(maxWidth: .infinity, maxHeight: .infinity)
  51. .background(Color.gray.opacity(0.2))
  52. .cornerRadius(10)
  53. .padding()
  54. }
  55. }
  56.  
  57. struct ContentView: View {
  58. var body: some View {
  59. PagingCardView(items: ["Card 1", "Card 2", "Card 3"])
  60. }
  61. }
  62.  
  63. @main
  64. struct MyApp: App {
  65. var body: some Scene {
  66. WindowGroup {
  67. ContentView()
  68. }
  69. }
  70. }
  71.  
  72. struct ViewOffsetKey: PreferenceKey {
  73. typealias Value = CGFloat
  74. static var defaultValue: CGFloat = 0
  75. static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
  76. value = nextValue()
  77. }
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement