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

℡╲_俬逩灬. 提交于 2019-12-11 17:22:41

问题


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.


回答1:


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




回答2:


You can use scrollViewDidScroll for this.

     func scrollViewDidScroll(scrollView: UIScrollView!) {
    if (self.lastContentOffset > scrollView.contentOffset.y) {
        // show your button
    }
    else if (self.lastContentOffset < scrollView.contentOffset.y) { 
       // hide your button
    }

    // update the new position acquired
    self.lastContentOffset = scrollView.contentOffset.y
}


来源:https://stackoverflow.com/questions/56787905/material-floating-action-button-should-invisible-when-user-scroll-down-and-visib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!