asheyla asheyla - 14 days ago 4x
Swift Question

Swift table view with few rows can be scrolled up

I have this table view which in some cases contains few rows, even one.
What’s wrong with it is that even if I have one row, it allows me to scroll down and the row gets hidden at top.

It practically almost disappears from screen, as if there would be somethingto show below it.
I can’t disable scrolling because I have pull down to refresh.

Any ideas if there is a setting I am missing? Or how I could not allow scroll down if I do not have enough rows to cover the whole screen?


Actually, your case is kind of tricky, because:

The first I thought that the solution will be myTableView.alwaysBounceVertical = false

That's will do the job for you, but the problem in your case that you have a UIRefreshControl() and setting alwaysBounceVertical to false will disable scrolling to top for displaying the refreshController.

So, it should be done manually, as follows:

1- Implement the scrollViewDidScroll method from UIScrollViewDelegate.

2- check the scrolling direction in it.

3- if the scrolling direction goes down, check if content size of the tableView is more than its height, i.e check if tableView contains cell more than its height.

4- if the output of step 3 is false, disable scrolling, else, enable scrolling.

5- add dispatch_after to re-enable tableView scrolling.

It goes like this (Note: Swift 2 code.):

private var lastContentOffset: CGFloat = 0
    // 1
    func scrollViewDidScroll(scrollView: UIScrollView) {
        // 2
        if (self.lastContentOffset > scrollView.contentOffset.y) {
            print("scrolling up")
        else if (self.lastContentOffset < scrollView.contentOffset.y) {
            print("scrolling down")

            // 3 and 4
            myTableView.scrollEnabled = myTableView.contentSize.height > myTableView.frame.size.height ? true : false

            // 5

            // delaying is half a second
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_MSEC) * 500), dispatch_get_main_queue(), { () -> Void in
                self.myTableView.scrollEnabled = true

Hope this is a good solution for your case.