1

我正在尝试在 UITableView 的最后一行实现自定义操作。

我找到了一个很好的扩展,以便知道我是否在最后一行:

extension UITableView {

    func isLast(for indexPath: IndexPath) -> Bool {

        let indexOfLastSection = numberOfSections > 0 ? numberOfSections - 1 : 0
        let indexOfLastRowInLastSection = numberOfRows(inSection: indexOfLastSection) - 1

        return indexPath.section == indexOfLastSection && indexPath.row == indexOfLastRowInLastSection
    }
}

我面临的唯一问题是,如果我的 tableView 有很多行,并且内容可滚动,那么最后一行是不可见的。因此,在我的 cellForRow 中,我正在这样做:

if tableView.isLast(for: indexPath) {
   print("Last Row - Do Specific action")
} else {
}

它正在工作,除了想象我的屏幕可以显示 6 行,但我的 tableView 的总行数是 15。它将在 indexPath 5 和 15 的行上应用我的特定操作。

我猜这是因为每次调用 cellForRow 时,它都会检查最后一行,并且它也适用于最后一个可见行。

如何仅在最后一行上实现自定义操作,即使它还不可见?

编辑:经过更多调查,问题来自 UITableView 无法预取单元格,并且 cellLoaded 和 cellVisible 是相同的。

4

3 回答 3

4

我无法复制粘贴代码,因为我现在没有 xcode。

但是,如果您想在单元格显示之前执行操作,请在

func tableView(_tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)

并检查最后一行:

if indexPath.row == dataSourceArray.count - 1 {
   //Perform action
}

dataSourceArray 是您从中获取数据以在单元格中显示的数组。

基本上你的代码应该是这样的

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
       if indexPath.row == dataSourceArray.count - 1 {
            //Perform action
    }
}

您可以通过苹果文档了解更多关于 tableview 委托方法的信息

于 2017-11-13T12:42:39.157 回答
0

在单元格中尝试此代码以获取行方法

if indexPath.row == yourarray.count - 1{

                // Put your code

        }
于 2017-11-13T11:25:00.180 回答
0

您可以尝试使用 tableview 委托方法:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) 
于 2017-11-13T11:07:23.737 回答