Issue
I wanted to create a custom carousel (in the future a snap carousel).
I tried to use a drag gesture but every time i drag it, it returns to 0 first, then drag the view. i tried to add the statingpoint value to the calculation, end up always starting at 500 ish
Are there any other method to do it? if not, how do i do it?
struct ScrollItem: View {
@Binding var offset:CGFloat
var body: some View {
HStack(spacing:10){
ForEach(0..<7){_ in
RoundedRectangle(cornerRadius: 10)
.frame(width: 200, height: 150, alignment: .center
}
}
.offset(x:offset)
.gesture(
DragGesture()
.onChanged({ val in
let startLoc = val.startLocation
self.offset = val.translation.width + startLoc.x // + startLoc.x
})
.onEnded({ val in
self.offset = val.translation.width
})
)
.animation(.easeInOut)
}
}
Solution
You need to keep track of the last offset.
struct ContentView: View {
@Binding var offset:CGFloat = .zero
@State var lastOffset: CGFloat = .zero
var body: some View {
HStack(spacing:10){
ForEach(0..<7){_ in
RoundedRectangle(cornerRadius: 10)
.frame(width: 200, height: 150, alignment: .center)
}
}
.offset(x:offset)
.gesture(
DragGesture()
.onChanged({ val in
self.offset = lastOffset + val.translation.width
})
.onEnded({ val in
lastOffset = offset
})
)
.animation(.easeInOut)
}
}
Answered By – mahan
Answer Checked By – Timothy Miller (BugsFixing Admin)