如何确定UITableView的最后一个单元格是否在屏幕上可见

时间:2017-09-14 00:05:19

标签: ios swift uitableview

我正在使用以下代码来确定屏幕上是否显示最后一个屏幕给用户:

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

这适用于小屏幕,用户必须滚动才能到达所需的单元格。但是,在整个表格可见的大屏幕上,此方法不起作用。有没有办法确定屏幕底部到UITableView的最后一个单元格之间的距离?

非常感谢任何帮助。谢谢。

编辑:这是我想要完成的。

if(最后一个单元格是可见的&&&&&&&&&&>屏幕底部的100dp){显示屏幕底部的固定按钮}否则{添加按钮到tableview的页脚视图,这样用户就可以向下滚动到按钮}

4 个答案:

答案 0 :(得分:2)

您可以使用此方法查看最后一个单元格是否可见

func isCellVisible(section:Int, row: Int) -> Bool {
    guard let indexes = self.indexPathsForVisibleRows else {
        return false
    }
    return indexes.contains {$0.section == section && $0.row == row }
}  }

Source

然后您可以将其称为

let lastCell = collection.count - 1
let result = isCellVisible(section:"Your Section Number", row: lastCell)

答案 1 :(得分:2)

我刚刚为您创建了一个项目,向您展示一种可能的解决方案(有很多)。

基本上你只需要使用

获取最后一个单元格位置
guard let lastCell = tableView.cellForRow(at: IndexPath(row: tableView.numberOfRows(inSection: 0)-1, section: 0)) else {
   return
}

let lastCellBottomY = lastCell.frame.maxY

然后知道tableView高度,您可以轻松计算最后一个单元格与屏幕底部之间的距离:

let delta = tableHeight - lastCellBottomY

并检查此距离是否足以显示或不显示固定按钮:

if delta > 55 { 
   // ...show button
} else {
   // ...hide button
} 

对于动态按钮(用户滚动时要在tableView的最后一个单元格下方添加的按钮),您可以添加一个带有自定义单元格的新部分来表示您的按钮。

您可以通过以下链接查看整个想法:

https://www.dropbox.com/s/7wpwv6737efnt5v/ButtonTable.zip?dl=0

如果您有任何疑问,请告诉我们。)

答案 2 :(得分:2)

试试吧!希望能帮到你。

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

答案 3 :(得分:0)

快速5

if let visiblePaths = tableView.indexPathsForVisibleRows,
    visiblePaths.contains([0, dataSourceArray.count - 1]) {

    // last cell is partially or fully visible

}

indexPathsForVisibleRowsIndexPath的数组。但是,有多种表达IndexPath的方式(它有7个不同的初始化器)。 indexPathsForVisibleRows包含IndexPath作为数组文字(即[0, 0]表示[节0,第0行])。因此,要使用indexPathsForVisibleRows,必须将路径声明为数组文字,而不是IndexPath(row: 0, section: 0)之类的其他形式。