ios – How do I know if scrollView has stopped in SwiftUI?


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()
        }
        
        
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img