Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if the last cell of a UITableView is visible on the screen

I'm using the following code to determine if the last screen is visible on the screen to the user:

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.row == collection.count - 1 {
        print("last cell is seen!!")
        print(cell.frame)
    }
}

This works on small screens where the user has to scroll to get to the desired cell. However, on large screens where the whole table is visible, this method doesn't work. Is there any way to determine the distance between bottom of screen to the last cell in the UITableView?

Any help would be greatly appreciated. Thank you.

Edit: this is what I'm trying to accomplish.

if (last cell is visible && it is more than 100dp from bottom of screen) { display a fixed button on bottom of screen } else { add button to footer view of tableview so the user can scroll down to the button }

like image 358
as diu Avatar asked Sep 14 '17 00:09

as diu


2 Answers

try it ! Hope to help you.

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let contentOffsetMaxY: Float = Float(scrollView.contentOffset.y + scrollView.bounds.size.height)
    let contentHeight: Float = Float(scrollView.contentSize.height)

    let ret = contentOffsetMaxY > contentHeight - 100
    if ret {
        print("testButton is show");
    }else{
        print("testButton is hidden");
    }
}
like image 164
CJiYI Avatar answered Sep 28 '22 09:09

CJiYI


Swift 5

if let visiblePaths = tableView.indexPathsForVisibleRows,
    visiblePaths.contains([0, dataSourceArray.count - 1]) {
    // last cell is at least partially visible
}

indexPathsForVisibleRows is an array of IndexPath. However, there are a number of ways to express IndexPath (it has 7 initializers). indexPathsForVisibleRows utilizes IndexPath as an array literal (i.e. [0, 0] or [section 0, row 0]); therefore, to use indexPathsForVisibleRows, you must declare the path as an array literal and not in any other way (i.e. IndexPath(row: 0, section: 0)).

like image 28
liquid LFG UKRAINE Avatar answered Sep 28 '22 08:09

liquid LFG UKRAINE