我希望在向下滚动时隐藏顶部,在向下滚动时隐藏底部的导航控制器(不在屏幕截图上),在向上滚动时重新显示。顶部是一个有两个按钮的图像。
最佳答案
您可以使用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
})
}
}
}
关于ios - 向下滚动时如何隐藏导航栏?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45118931/