这是我的代码的一部分:
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”。
谢谢!
如果您不想修改原始数组,可以创建第二个数组以记录要重复的数组:
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
}
笔记:
repeats
数组,重新加载你的tableView
。repeats = []
。"a", "b", "c", "a", "a", "a"
,请将重复项设置为[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
}