向下滚动时如何隐藏导航栏?

时间:2017-07-15 13:47:47

标签: ios swift user-interface swift3 storyboard

当我向下滚动时,顶部部分隐藏,底部的导航控制器(屏幕截图中没有)在我向下滚动时隐藏,在向上滚动时重新出现。顶部是带有两个按钮的图像。

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用scrollView委托。例如

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView.panGestureRecognizer.translation(in: scrollView.superview).y > 0 {
        //scrolling downwards
        if scrollView.contentOffset.y < 0 {
            //this means we are at top of the scrollView
            changeSectionHeight(with scrollView.contentOffset.y, hide:false)
        }
    }
    else {
        //we are scrolling upward
       changeSectionHeight(with scrollView.contentOffset.y, hide:true)
    }
}

这是您在用户向下或向上滚动时的方式。现在基于我们可以隐藏或显示顶部(通过更改高度约束)。

//make IBoutlet for the top section height constraint
@IBOutlet weak var topSectionHeightConstraint: NSLayoutConstraint!

func changeSectionHeight(with offset:CGFloat, hide:Bool) {

    let requiredHeight: CGFloat = hide ? 0.0 : 160.0  //let say when you want to hide the height is 0.0 and when you want to show it its 160.0

    //If you want animation when showing and hiding use animate if not then simply change the constant for the constraint
    if hide {
        if (holderViewHeightConstraint.constant - offset) > requiredHeight {
            UIView.animate(withDuration: 0.3, animations: {
                self. topSectionHeightConstraint.constant -= offset
            })
        }
        else {
            UIView.animate(withDuration: 0.3, animations: {
                self. topSectionHeightConstraint.constant = requiredHeight
            })
        }
    }
    else {
        if (holderViewHeightConstraint.constant - offset) < requiredHeight {
            UIView.animate(withDuration: 0.3, animations: {
                self. topSectionHeightConstraint.constant -= offset
            })
        }
        else {
            UIView.animate(withDuration: 0.3, animations: {
                self. topSectionHeightConstraint.constant = requiredHeight
            })
        }
    }
}