向下滚动以逐渐隐藏菜单栏或查看并向上滚动

klk*_*lkl 0 uiviewcontroller ios uicollectionview swift

我想在 collectionview 之上创建一个菜单栏。当用户向下滚动时,菜单栏会逐渐隐藏,但当用户向上滚动时,菜单栏会立即出现。行为类似于导航栏的 hidewhenswipe 功能。是否有任何解决方案可以在此菜单栏上创建此类行为?谢谢。

[截屏]1

Sah*_*nda 5

  1. 如果还没有给你的标题视图一个高度限制。然后连接该约束,例如

    @IBOutlet 弱 var headerViewHeightConstraint: NSLayoutConstraint!

  2. 确认您的 ViewController 到 UICollectionViewDelegate 和 UIScrollViewDelegate

  3. 在 ViewDidLoad() 中设置 collectionView.delegate = self

  4. UICollectionView 是 UIScrollView 的子类,因此您可以覆盖scrollViewDidScroll的委托方法并使用以下代码

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.contentOffset.y > 50 {// the value when you want the headerview to hide
        view.layoutIfNeeded()
        headerViewHeightConstraint.constant = 0
        UIView.animate(withDuration: 0.5, delay: 0, options: [.allowUserInteraction], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
    
    }else {
        // expand the header
        view.layoutIfNeeded()
        headerViewHeightConstraint.constant = 100 // Your initial height of header view
        UIView.animate(withDuration: 0.5, delay: 0, options: [.allowUserInteraction], animations: {
            self.view.layoutIfNeeded()
        }, completion: nil)
     }
    }
    
    Run Code Online (Sandbox Code Playgroud)