10

在 swift 3 之前,我曾经使用例如:

let path = self.tableView.indexPathForSelectedRow
if (path != NSNotFound) {
//do something
 }

但是现在,由于我IndexPath在 swift3 中使用类,我正在寻找 path != NSNotFound检查的等价物。

Xcode8.3.1 编译器错误: “二元运算符'!='不能应用于'IndexPath'和'Int'类型的操作数”

4

4 回答 4

20

为了检查是否IndexPath存在,我使用了这个扩展函数:

import UIKit

extension UITableView {

    func hasRowAtIndexPath(indexPath: IndexPath) -> Bool {
        return indexPath.section < self.numberOfSections && indexPath.row < self.numberOfRows(inSection: indexPath.section)
    }
}

为了使用它,我做了这样的事情:

if tableView.hasRowAtIndexPath(indexPath: indexPath) {
    // do something
}
于 2017-04-25T18:12:56.340 回答
11

从语义上讲,要考虑 indexPath无效,您需要检查某些内容,例如表视图或集合视图。

通常,如果indexPath表示数据源中没有相应数据的行,则可以认为它无效。(一个例外是“加载更多”行。)

如果你真的需要创建一个 invalid IndexPath,你可以这样做:

let invalidIndexPath = IndexPath(row: NSNotFound, section: NSNotFound)

更新后:

self.tableView.indexPathForSelectedRownil如果没有选定的行,则返回一个 Optional 。

if let path = tableView.indexPathForSelectedRow {
  // There is a selected row, so path is not nil.
}
else {
  // No row is selected.
}

无论如何,在所有情况下进行比较path都会NSNotFound引发异常。

于 2017-04-25T15:22:00.720 回答
0

通过@pableiros 改进答案以处理部分或行小于0 的边缘情况。当表为空并且您尝试通过 访问它时会发生这种情况listOfSectionHeaders.count - 1listOfRowsForSection.count - 1

extension UITableView {
    func isValid(indexPath: IndexPath) -> Bool {
        return indexPath.section >= 0 && indexPath.section < self.numberOfSections && indexPath.row >= 0 && indexPath.row < self.numberOfRows(inSection: indexPath.section)
    }
}
于 2021-01-15T06:39:51.187 回答
0

我偶然发现了collectionView(_:didEndDisplaying:forItemAt:)返回无效 indexPath 的情况,因此我曾经indexPath.isEmpty检查 indexPath 是否确实是行/节 indexPath。

于 2021-02-25T13:40:46.853 回答