问题
I have material Floating action button (FAB) at right bottom of screen. Also, I have CollectionView inside View. I want below actions to be done.
- When user scrolls down - FAB should invisible.
- When user scrolls up - FAB should visible.
I've searched everywhere in google.None of questions satisfied my requirements.
回答1:
don't forget to set collectionView.delegate = self.
extension ViewController: UIScrollViewDelegate{
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectoinView{
button.isHidden = scrollView.contentOffset.y > 50
}
}
}
50 is the position of Y from which the button will hide. You can adjust to any number according to your requirement.
Another Way of doing that
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")
}
}
with the second approach, there is no need to provide static value. the second approach has been converted to Swift from objective-c Answer
回答2:
You can use scrollViewDidScroll for this.
func scrollViewDidScroll(scrollView: UIScrollView!) {
if (self.lastContentOffset > scrollView.contentOffset.y) {
// show your button
}
else if (self.lastContentOffset < scrollView.contentOffset.y) {
// hide your button
}
// update the new position acquired
self.lastContentOffset = scrollView.contentOffset.y
}
来源:https://stackoverflow.com/questions/56787905/material-floating-action-button-should-invisible-when-user-scroll-down-and-visib