首页 > 解决方案 > 当用户向下滚动和向上滚动时,材质浮动操作按钮应该不可见

问题描述

我在屏幕右下方有材质浮动操作按钮 (FAB)。另外,我在 View 中有 CollectionView。我希望完成以下操作。

  1. 当用户向下滚动时 - FAB 应该不可见。
  2. 当用户向上滚动时 - FAB 应该可见。

我在谷歌到处搜索。没有一个问题能满足我的要求。

标签: iosswiftuicollectionviewuiscrollview

解决方案


不要忘记设置 collectionView.delegate = self.

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

50Y的位置,按钮将从该位置隐藏。您可以根据您的要求调整到任何数字。


另一种方法

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

使用第二种方法,不需要提供静态值。第二种方法已从objective-c Answer转换为Swift


推荐阅读