【问题标题】:Swift - How to do specific action on last row of a UITableView when the last row isn't visible?Swift - 当最后一行不可见时,如何对 UITableView 的最后一行执行特定操作?
【发布时间】:2017-11-13 11:02:59
【问题描述】:

我正在尝试在 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 是相同的。

【问题讨论】:

  • 您要对哪个事件应用操作?我的意思是最初当 tableview 加载或任何其他时?
  • 加载时,最终在显示之前。
  • 您想对最后一行执行什么操作。它是快速任务上的长时间运行任务吗?
  • 更改标签、图像、文本等。但我不能在数据源上这样做
  • 除非您的索引路径不可见,否则您将无法自定义单元格引用

标签: ios swift uitableview row indexpath


【解决方案1】:

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

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

中执行

func tableView(_tableView: UITableView, willDisplay单元格: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
    }
}

您可以通过apple docs 了解更多关于 tableview 委托方法的信息

【讨论】:

  • 如果我想修改单元格的属性,如果它是最后一个单元格,我应该重新加载数据还是在主线程中执行?
  • 重新加载单元格。但是您需要小心 indexPath,因为如果同时滚动和重新加载,它可能会崩溃。为此,您的 dataModel 必须更新。
  • @Balanced 如果它帮助您解决了您在问题中提出的问题,请接受答案:)
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    在单元格中尝试此代码用于行方法

    if indexPath.row == yourarray.count - 1{
    
                    // Put your code
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      相关资源
      最近更新 更多