arrays - 在 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”。
谢谢!
解决方案
如果您不想修改原始数组,可以创建第二个数组来记录要重复的数组:
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]
。
推荐阅读
- python - Tensorflow:如何使用 tf 数据集构建高效的 NLP 管道
- apache-spark - Apache Airflow - Spark 提交失败 - 使用主 'yarn-client' 运行时,必须在环境中设置 HADOOP_CONF_DIR 或 YARN_CONF_DIR
- ansible - 通过删除ansible中的进程ID来停止任务
- android - View.setPadding 影响背景 ShapeDrawable 填充
- regex - 仅获取 UUID 而不是全部
- javascript - 如何将 state 中定义的数组中的值传递给看到组件的组件?
- angular - ngx-translate 不适用于 Angular 8 的生产模式
- python - 如何使用请求库登录本网站?
- regex - 正则表达式:有一个单行符吗?
- git - 如何通过 SSH 修复 GitLFS 授权错误?