1 row uitableview ios swift indexpath
我试图在 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
}
}
Run Code Online (Sandbox Code Playgroud)
我面临的唯一问题是,如果我的 tableView 有很多行且内容可滚动,则最后一行不可见。因此,在我的 cellForRow 中我正在这样做:
if tableView.isLast(for: indexPath) {
print("Last Row - Do Specific action")
} else {
}
Run Code Online (Sandbox Code Playgroud)
它正在工作,除了假设我的屏幕可以显示 6 行,但我的 tableView 的总行数是 15 。它将在 indexPath 5 和 15 处的行上应用我的特定操作。
我猜测这是因为每次调用 cellForRow 时,它都会检查最后一行,并且它也适用于最后一个可见行。
如何仅在最后一行实现自定义操作,即使它还不可见?
编辑:经过更多调查,问题来自 UITableView 无法预取单元格,并且 cellLoaded 和 cellVisible 是相同的。
我无法复制粘贴代码,因为我现在没有 xcode。
但是,如果您想在显示单元格之前执行操作,请在
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
并检查最后一行:
if indexPath.row == dataSourceArray.count - 1 {
//Perform action
}
Run Code Online (Sandbox Code Playgroud)
dataSourceArray 是您从中获取数据以将其显示在单元格中的数组。
基本上你的代码应该是这样的
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if indexPath.row == dataSourceArray.count - 1 {
//Perform action
}
}
Run Code Online (Sandbox Code Playgroud)
您可以浏览苹果文档以了解有关 tableview delegate 方法的更多信息
| 归档时间: |
|
| 查看次数: |
8260 次 |
| 最近记录: |