Search code examples
iosswiftuicollectionviewuiscrollview

Material floating action button should invisible when user scroll down and visible when scrolls up


I have material Floating action button (FAB) at right bottom of screen. Also, I have CollectionView inside View. I want below actions to be done.

  1. When user scrolls down - FAB should invisible.
  2. When user scrolls up - FAB should visible.

I've searched everywhere in google.None of questions satisfied my requirements.


Solution

  • don't forget to set collectionView.delegate = self.

    extension ViewController: UIScrollViewDelegate{
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if scrollView == collectoinView{
                button.isHidden = scrollView.contentOffset.y > 50
            }
        }
    }
    

    50 is the position of Y from which the button will hide. You can adjust to any number according to your requirement.


    Another Way of doing that

    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    
        let targetPoint = targetContentOffset as? CGPoint
        let currentPoint = scrollView.contentOffset
    
        if (targetPoint?.y ?? 0.0) > currentPoint.y {
            print("up")
    
        } else {
            print("down")
         }
    }
    

    with the second approach, there is no need to provide static value. the second approach has been converted to Swift from objective-c Answer