Повторение n-индекса массива в табличном представлении в swift 4.2 - PullRequest
0 голосов
/ 14 марта 2019

Это часть моего кода:

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".

Спасибо!

Ответы [ 2 ]

0 голосов
/ 14 марта 2019

Для последовательностей:

["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
}
0 голосов
/ 14 марта 2019

Если вы не хотите изменять исходный массив, вы можете создать второй массив, чтобы отметить, какие из них повторить:

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].
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...