I want the top section to hide when I scroll down and the navigation controller at the bottom (which isn't on the screenshot) to hide when I scroll down and reappear when scrolling up. The top part is an image with two buttons.
Asked
Active
Viewed 1,453 times
1 Answers
1
you could use the scrollView delegates for this. For example
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)
}
}
This is how you will know when the user is scrolling down or up. Now based on that we can hide or show the top section (by changing the height constraint).
//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
})
}
}
}

kathayatnk
- 975
- 1
- 7
- 9
-
how would changing the height constraint look like in code? – Riccardo Jul 15 '17 at 17:44
-
added a function to change the height. Not tested, but you can tweak for your desired results. – kathayatnk Jul 15 '17 at 18:02