在swift 4.2中的表视图中重复数组的n索引

问题描述 投票:0回答:2

这是我的代码的一部分:

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”。

谢谢!

arrays swift uitableview
2个回答
0
投票

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

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]

0
投票

对于序列:

[“a”,“b”,“c”],[“a”,“b”,“c”],[“a”,“b”,“c”]等。

或逆转

[“a”,“b”,“c”],[“c”,“b”,“a”],[“a”,“b”,“c”]等。

let repeateCount = 4
let reverse = false
let array = ["a","b","c"]

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    var index = indexPath.row % array.count
    if reverse {
        if (indexPath.row / array.count) % 2 != 0 { // odd
            index = array.count - index - 1
        }
    }
    let someWord = array[index]
    return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.