2017-09-14 22 views
3

我用下面的代码,以确定最后的画面是在屏幕上向用户可见可见:如何确定一个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最后一个单元之间的距离?

任何帮助将不胜感激。谢谢。

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

如果(最后一个单元是可见& &其大于100dp从屏幕底部){在屏幕上显示的底部的固定按钮}否则{添加按钮的tableview的页脚视图,以便用户可以向下滚动到按钮}

+0

但是,为什么你想知道这一点? – Siyavash

+0

if(最后一个单元格可见&&它从屏幕底部超过100dp){在屏幕底部显示一个固定按钮} else {将按钮添加到tableview的页脚视图,以便用户可以向下滚动到按钮} 是我需要这样做的主要原因。感谢您的回应。 –

+0

现在有意义了,请将其添加到问题中。也有你试着看着方法“didEndDisplaying” – Siyavash

回答

1

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

基本上你只需要获得最后一个单元格位置,使用

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

让我知道如果您有任何疑问:)

1

您可以使用此方法来看看最后一个单元是可见或不可见

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

试试吧!希望能帮助你。

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"); 
    } 
} 
相关问题