【问题标题】:why the index.row recounting when I scroll the tableview为什么当我滚动表格视图时 index.row 重新计数
【发布时间】:2018-05-27 10:57:48
【问题描述】:

在这里,我想使用 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
}

【问题讨论】:

  • 这就是cell复用的核心。一旦单元格从屏幕上滚出,它就会被重复使用,并且在您向后滚动时必须重新设置。
  • @Sulthan 嗯,但这种重新计票情况只发生一次。从 4 开始重新计数后,将永远不会重新计数,并一直计数到 50。
  • @OttoYing:调用数据源方法的频率和顺序无关紧要。如果这会影响您的程序,那么您在其他地方会出现编程错误。
  • 目前还不清楚你的实际问题是什么......
  • cellForRowAt 正在索引self.wallpaperIDList 时,为什么numberOfRowsInSection50 硬编码?您的numberOfRowsInSection 需要返回self.wallpaperIDList.count

标签: ios swift uitableview


【解决方案1】:

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

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

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

【讨论】:

  • 好的,谁否决了我的回答?如果您认为我的回答很差,请说明原因,以便我改进。
【解决方案2】:

无论是否重新计算,索引行都不重要。它不会影响 tableview 显示其数据的方式。我已经运行了我的代码,结果和我预期的一样完美。

【讨论】:

  • 对。正如我和其他几个人告诉你的那样,你不应该假设表格视图在调用tableView(cellForRowAt:) 数据源方法时会请求特定的IndexPaths。如果它决定请求同一个单元 20 次,您应该只交付该单元 20 次,并且您的代码不应假设它将请求哪些单元。调用的数据源方法也不应该有副作用。
猜你喜欢
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2016-07-20
相关资源
最近更新 更多