struct CarouselView<Content: View>: View {
private var numberOfItems: Int
private var content: Content
@State private var currentIndex: Int = 0
init(numberOfItems: Int, @ViewBuilder content: () -> Content) {
self.numberOfItems = numberOfItems
self.content = content()
}
var body: some View {
GeometryReader { geometry in
HStack(spacing: 0) {
self.content
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .leading)
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .leading)
.offset(x: -CGFloat(self.currentIndex) * geometry.size.width, y: 0)
.animation(.spring())
.gesture(
DragGesture()
.onEnded({ value in
if value.translation.width < 0 {
if self.currentIndex < self.numberOfItems - 1 {
self.currentIndex += 1
}
}
if value.translation.width > 0 {
if self.currentIndex > 0 {
self.currentIndex -= 1
}
}
})
)
}
}
}
댓글