Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop overscroll UITableView only at the top?

There is similar question Stop UITableView over scroll at top & bottom?, but I need slighty different functionality. I want my table so that it can be overscrolled at the bottom, but cannot be overscrolled at the top. As I understood,

tableView.bounces = false

Allows to disable overscrolling at both top and bottom, however, I need disabling this only at the top. Like

tableView.bouncesAtTheTop = false
tableView.bouncesAtTheBottom = true
like image 659
caffeinum Avatar asked Jun 25 '16 15:06

caffeinum


2 Answers

For Swift 2.2, Use

func scrollViewDidScroll(scrollView: UIScrollView) {
    if scrollView == self.tableView {
        if scrollView.contentOffset.y <= 0 {
            scrollView.contentOffset = CGPoint.zero
        }
    }
}

For Objective C

    -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentOffset.y<=0) {
        scrollView.contentOffset = CGPointZero;
    }
}
like image 95
Mohsin Qureshi Avatar answered Sep 29 '22 07:09

Mohsin Qureshi


You can achieve it by changing the bounce property in scrollViewDidScroll of the tableView (you need to be the delegate of the tableView)

Have a property for the lastY:

var lastY: CGFloat = 0.0

Set initial bounce to false in viewDidLoad:

tableView.bounces = false

and:

func scrollViewDidScroll(scrollView: UIScrollView) {
    let currentY = scrollView.contentOffset.y
    let currentBottomY = scrollView.frame.size.height + currentY
    if currentY > lastY {
        //"scrolling down"
        tableView.bounces = true
    } else {
        //"scrolling up"
        // Check that we are not in bottom bounce
        if currentBottomY < scrollView.contentSize.height + scrollView.contentInset.bottom {
            tableView.bounces = false
        }
    }
    lastY = scrollView.contentOffset.y
}
like image 38
oren Avatar answered Sep 29 '22 08:09

oren