首页 > 解决方案 > 为什么当我滚动表格视图时 index.row 重新计数

问题描述

在这里,我想使用 index.row 来索引 Array,但奇怪的是 index.row 会在我滚动 tableView 时重新计数。有什么解决办法吗?或另一种索引数组的方法?

就像下面这样:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4 #recount from 4
5
6
7
8
9
10

这是源代码:

func tableviewSetUp() {
    let rect = self.view.frame
    self.tableView = UITableView(frame: rect)
    self.tableView.backgroundColor = UIColor.black
    self.tableView.delegate = self
    self.tableView.dataSource = self
    self.view.addSubview(self.tableView)
    self.tableView.register(WallpaperTableViewCell.self, forCellReuseIdentifier: "wallpaperCell")
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "wallpaperCell", for: indexPath) as! WallpaperTableViewCell
    print(indexPath.row)  //here I print the row number
    let wallpaper = self.wallpaperIDList[indexPath.row]//here I using the index.row to index the array
    return cell
}
func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 50
}

标签: iosswiftuitableview

解决方案


表视图将调用它们认为合适的数据源方法。您不应该对将传递给的 IndexPaths 做出任何假设tableView(cellForRowAt:)。在被问到时返回单元格。

如果它要求第 4 行两次,则给它第 4 行两次。

应该使用数组作为数据模型。这是表示单个截面表视图的数据的一种非常好的方法。表视图两次请求索引 4 处的行这一事实并没有改变这一点。(或将数组数组用于分段表视图。)


推荐阅读