首页 > 解决方案 > 如何在 iOS 的 tableview 中找到第 n 个索引路径?

问题描述

我有一个包含多个section的tableview,每个section有不止一行,但是section中的行数不相等,像这样

first 1
"row 1.1"

second 2
"row 2.1"
"row 2.2"
"row 2.3"----->

second 3
"row 3.1"
"row 3.2"
"row 3.3"
"row 3.4"
"row 3.5"
"row 3.6"

我想获取 tableview 中的第 4 个元素,即“row 2.3”
它的索引路径是 [1, 2]
我应该如何获取这个索引路径?

我的解决方案是在 tableview 中找到“第 2.3 行”,然后找到它的 indexPath。还有其他方法可以获取第 n 个元素索引路径吗?

标签: swifttableview

解决方案


你可以试试

var neededNumber = 5 - 1 // 5th element

var index:IndexPath?

for sec in 0..<tableView.numberOfSections {

    if neededNumber < tableView.numberOfRows(inSection: sec) {

        index = IndexPath(row: neededNumber, section: sec)

        break
    }
    else
    {
        neededNumber -= tableView.numberOfRows(inSection: sec)
    }

 }

if let myIndex = index {

    print(myIndex)

}

推荐阅读