How can I handle
scrollViewDidEndDecelerating and scrollViewDidEndDragging function in swiftUI
I want to set the position of the scrollView so that the selectedIndex is in the middle when the scrollView stops moving.
struct ContentView: View {
@State private var imageList: [String] = ["Onur","Onur","Onur","Onur","Onur","Onur","Onur","Onur","Onur"]
private var spacing: CGFloat = UIScreen.main.bounds.width / 2 - 100
@State private var moffsetX: CGFloat = 0
@State private var oldFffsetX: CGFloat = 0
@State private var isScrolling: Bool = false
@State private var selectedIndex: Int = 0
func horizontalScrollView() -> some View {
ScrollView(.horizontal){
Spacer()
HStack(spacing: spacing){
Spacer()
.frame(width: 50)
ForEach(imageList, id:.self){ image in
Image(image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 100,height: 100)
.clipShape(Circle())
.overlay(Circle().stroke(.blue,lineWidth: 4))
}
Spacer()
.frame(width: 50)
}
.overlay(GeometryReader{ geometry in
Color.clear.onChange(of: geometry.frame(in: .global).minX) { value, newValue in
oldFffsetX = value
moffsetX = newValue
let index = Int(round(geometry.frame(in: .global).minX / (-1 * (100 + spacing))))
if index != selectedIndex{
if index < 0{
selectedIndex = 0
} else if index > imageList.count - 1{
selectedIndex = imageList.count - 1
} else{
selectedIndex = index
}
}
isScrolling = true
}
})
Spacer()
}
}
}
2
Answers
You can consider using the CurrentValueSubject with the AnyPublisher to detect the scroll events. Here’s the demonstration of the use case,
Add this
PreferenceKey
to track the vertical scroll offset of aView
:Add this
ViewModifier
to allow tracking of a View’s vertical offset and call ascrollPostionUpdate
closure when scrolling has stopped:Usage: Add the
.onScrollEnded
modifier to the content of theScrollView
and give theScrollView
a coordinateSpace name: