首页 > 解决方案 > 在 swift 4.2 中的表视图中重复数组的 n 索引

问题描述

这是我的代码的一部分:

let array = ["a","b","c"]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return array.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    let someWord = array[indexPath.row]
    return cell
}

如何再显示一次 n-index?例如:“a”、“b”、“c”、“a”或“a”、“b”、“c”、“c”。

谢谢!

标签: arraysswiftuitableview

解决方案


如果您不想修改原始数组,可以创建第二个数组来记录要重复的数组:

let array = ["a","b","c"]

// indices of array to repeat - 2 will repeat "c"
var repeats = [2]

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // Number of cells in the table is the sum of the counts of both arrays
    return array.count + repeats.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

    let someWord: String

    // Get the proper item from the array
    if indexPath.row < array.count {
        someWord = array[indexPath.row]
    } else {
        someWord = array[repeats[indexPath.row - array.count]]
    }

    // Do something with someWord

    return cell
}

笔记:

  1. 每当您修改repeats数组时,请重新加载您的tableView.
  2. 如果您不想重复任何项目,请设置repeats = [].
  3. 该数组允许您重复多个项目或单个项目多次:要获取"a", "b", "c", "a", "a", "a",请将重复设置为[0, 0, 0]

推荐阅读