caffeinum
caffeinum

Reputation: 431

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

Upvotes: 6

Views: 6696

Answers (2)

Mohsin Qureshi
Mohsin Qureshi

Reputation: 1213

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;
    }
}

Upvotes: 12

oren
oren

Reputation: 3209

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
}

Upvotes: 3

Related Questions