apptekstudios / ASCollectionView

A SwiftUI collection view with support for custom layouts, preloading, and more.
MIT License
1.36k stars 160 forks source link

scrollPositionSetter is not working #220

Open leogiroux opened 3 years ago

leogiroux commented 3 years ago

Hi,

Nothing is happening when I set the scroll position in my example, am I doing something wrong ?

    @State var asCollectionViewScrollPosition: ASCollectionViewScrollPosition? = ASCollectionViewScrollPosition.top

           ASCollectionView(sections: self.sections)
                .layout { sectionID in
                    if sectionID != "header" {
                        return self.getCategoryLayout()
                    } else if sectionID == "header" {
                        return self.getDefaultLayout(estimatedHeight: 130)
                    } else {
                        return self.getDefaultLayout()
                    }
                }
                .onScroll({ point, size in
                    print("point \(point.y)")
                    if point.y > 100  {
                        withAnimation(.spring()) { isTopBarVisible = true }
                    } else {
                        withAnimation(.spring()) { isTopBarVisible = false }
                    }
                })
                .scrollPositionSetter($asCollectionViewScrollPosition)
                .contentInsets(.init(top: 10, left: 0, bottom: 10, right: 0))
                .hideNavBar()

            Button {
                print("search button clicked")
                withAnimation {
                    asCollectionViewScrollPosition = ASCollectionViewScrollPosition.indexPath(IndexPath(row: 0, section: 0), positionOnScreen: .top, extraOffset: CGPoint(x: 0, y: 0))
                }
            } label: {
                Image(systemName: "magnifyingglass")
                    .resizable()
                    .foregroundColor(.white)
                    .frame(width: 24, height: 24, alignment: .topTrailing)
                    .padding()
            }
kevindropwithus commented 3 years ago

I'm experiencing the same

r3pps commented 3 years ago

I was experiencing this issue as well, but I have seemed to find a fix, what I did was added this to the updateUIViewController method in ASTableView file:

    context.coordinator.applyScrollPosition(animated: true)

This way, when the binding gets updated, the updateUIViewController method is triggered, and this forces the coordinator the apply the new scroll position. Hope this helps!

P.S. The same should also work by adding this line to the updateUIViewController method in the ASCollectionView file