代码之家  ›  专栏  ›  技术社区  ›  Fattaneh Talebi

如何在iOS中找到TableView中的第n个索引路径?

  •  -1
  • Fattaneh Talebi  · 技术社区  · 8 年前

    我有一个带有多个部分的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中的第4个元素,即“row 2.3”
    其索引路径为[1,2]
    如何获取此索引路径?

    我的解决方案是在TableView中找到“row 2.3”,然后找到它的indexPath。是否有其他方法来获取第n个元素索引路径?

    3 回复  |  直到 8 年前
        1
  •  1
  •   Martin R    8 年前

    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
            }
        }
    }
    

    tableView.indexPath(forIndex: 0)

        2
  •  1
  •   Vyacheslav    8 年前
    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
    }
    
        3
  •  1
  •   Shehata Gamal    8 年前

    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)
    
    }