Swift 如何找到n';iOS中tableview中的第个索引路径?
我有一个包含多个分区的tableview,每个分区都有多行,但是分区中的行数不相等,如下所示Swift 如何找到n';iOS中tableview中的第个索引路径?,swift,tableview,Swift,Tableview,我有一个包含多个分区的tableview,每个分区都有多行,但是分区中的行数不相等,如下所示 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中的第四个元素,即“第2.3行” 其索引路径为[1,2] 如何获取此索引路径 我的解决方案是在table
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中的第四个元素,即“第2.3行”其索引路径为[1,2]
如何获取此索引路径 我的解决方案是在tableview中找到“Row2.3”,然后找到它的indexPath。是否有其他方法获取第n个元素索引路径?您可以尝试
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)
}
var neededNumber=5-1//5个元素
var索引:indexath?
对于0..中的秒,您必须在部分上循环,减去中的行数
从给定索引中删除当前节,直到该索引是当前节中的有效行号为止。类似这样(未经测试):
扩展UITableView{
func indexath(forIndex索引:Int)->indexath{
var行=索引
var段=0
而section=self.numberOfRows(第节:section){
行-=self.numberOfRows(第节)
截面+=1
}
如果节
(假定给定的索引是基于零的,即tableView.indexath(forIndex:0)
返回第一个有效的索引路径
funcindexath(对于索引:Int)->indexath?{
变量计数器=0
对于0.中的sectionIndex,您是否需要始终获取2.3项或放置在TableView第四位的任何内容从您的模型中读取它可能…?@praventate第四位没有任何内容也可能需要设置var row=index-1@Sh_Khan:这取决于您的计数方式。对于第一个表视图单元格,我总是使用index=0。op给出1基value@Sh_Khan:你是对的,因此我在这里澄清了这一点。
extension UITableView {
func indexPath(forIndex index: Int) -> IndexPath? {
var row = index
var section = 0
while section < self.numberOfSections && row >= self.numberOfRows(inSection: section) {
row -= self.numberOfRows(inSection: section)
section += 1
}
if section < self.numberOfSections {
return IndexPath(row: row, section: section)
} else {
return nil
}
}
}
func indexPath(for index: Int) -> IndexPath? {
var counter = 0
for sectionIndex in 0..<tableView.numberOfSections {
for rowIndex in 0..<tableView.numberOfRows(inSection: sectionIndex) {
if index == counter {
return IndexPath(row: rowIndex, section: sectionIndex)
}
counter += 1
}
}
return nil
}