[英]How to determine if the last cell of a UITableView is visible on the screen
我正在使用以下代碼來確定用戶是否可以在屏幕上看到最后一個屏幕:
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){ 在屏幕底部顯示一個固定按鈕 } else { 添加按鈕到 tableview 的頁腳視圖,以便用戶可以向下滾動到按鈕 }
嘗試一下 ! 希望能幫到你。
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");
}
}
我剛剛為您創建了一個項目,向您展示一種可能的解決方案(有很多)。
基本上你只需要得到最后一個單元格位置,使用
guard let lastCell = tableView.cellForRow(at: IndexPath(row: tableView.numberOfRows(inSection: 0)-1, section: 0)) else {
return
}
let lastCellBottomY = lastCell.frame.maxY
然后知道tableView的高度,就可以很容易的計算出最后一個cell到屏幕底部的距離了:
let delta = tableHeight - lastCellBottomY
並檢查此距離是否足以讓您顯示固定按鈕:
if delta > 55 {
// ...show button
} else {
// ...hide button
}
對於動態按鈕(當用戶滾動時您想在 tableView 的最后一個單元格下方添加的按鈕),您只需添加一個帶有自定義單元格的新部分來代表您的按鈕。
您可以通過此鏈接查看整個想法:
https://www.dropbox.com/s/7wpwv6737efnt5v/ButtonTable.zip?dl=0
如果您有任何問題,請告訴我 :)
斯威夫特 5
if let visiblePaths = tableView.indexPathsForVisibleRows,
visiblePaths.contains([0, dataSourceArray.count - 1]) {
// last cell is partially or fully visible
}
indexPathsForVisibleRows
是一個IndexPath
數組。 但是,有多種方法可以表示IndexPath
(它有 7 個不同的初始值設定項)。 indexPathsForVisibleRows
包含IndexPath
作為數組文字(即[0, 0]
表示 [section 0, row 0])。 因此,要使用indexPathsForVisibleRows
,您必須將路徑聲明為數組文字,而不是另一種形式,例如IndexPath(row: 0, section: 0)
。
您可以使用此方法查看最后一個單元格是否可見
func isCellVisible(section:Int, row: Int) -> Bool {
guard let indexes = self.indexPathsForVisibleRows else {
return false
}
return indexes.contains {$0.section == section && $0.row == row }
} }
然后你可以這樣稱呼它
let lastCell = collection.count - 1
let result = isCellVisible(section:"Your Section Number", row: lastCell)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.