【问题标题】:How to prevent tableview refreshing cell data when scrolling down?向下滚动时如何防止tableview刷新单元格数据?
【发布时间】:2022-06-10 18:28:42
【问题描述】:

我对 swift 还很陌生,想创建一个表格视图来记录体育比赛的精彩片段(例如时间、事件、比分)。我让它工作,但每当我向下滚动超过最大单元格数时,您可以立即查看较早的单元格刷新到最新值,例如时间将更改为当前时间。我希望找到一种方法来防止这种情况发生。

这是我当前的表格视图代码。我的 tableview 表示为 Gamelog。非常感谢任何帮助!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        Gamelog.backgroundColor = UIColor.clear
        return NumberofScores
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = (self.Gamelog.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell?)!
        cell.textLabel?.text = TimerLabel.text! + " " + "Score:" + " " + AScore.text! + "-" + BScore.text! + Gamelogtext
        cell.textLabel?.adjustsFontSizeToFitWidth = true
        cell.backgroundColor = UIColor(red: 0/255, green: 144/255, blue: 81/255, alpha: 1)
        cell.textLabel?.textColor = UIColor.white
       
                return cell
    }
    let cellReuseIdentifier = "cell"

//This is what I use when a button is pressed to input a cell.

Gamelogtext = " - " + TeamA.text! + " TRY " + A1.text!
                self.Gamelog.performBatchUpdates({
                        self.Gamelog.insertRows(at: [IndexPath(row: NumberofScores-1,
                                                                 section: 0)],
                                                  with: .automatic)
                    }, completion: nil)

【问题讨论】:

  • 这就是 UITableView 的工作原理。这样做是为了让您不会遇到数百个单元的内存问题。您不应该禁用此功能。这个工作方式有问题吗?

标签: ios swift uitableview


【解决方案1】:

您使用表格视图来表示您的数据,该数据通常是一个数组。所以你应该从那里开始。

private var allScores: [Scores] = []

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { allScores.count }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as! ScoreTableViewCell
    cell.setupWithScore(allScores[indexPath.row])
    return cell
}

主要是当你设置一个包含数据的单元格时,你需要以某种方式使用你收到的索引路径allScores[indexPath.row]。即使您使用基本的非子类UITableViewCell 并分配给textLabel

当您将数据添加到表视图时,您还需要更新您的数组。比如

self.allScores.append(.init())
self.Gamelog.insertRows(at: [IndexPath(row: NumberofScores-1, section: 0)], with: .automatic)

这将使用您插入的新索引路径触发您的cellForRowAt,您可以使用该索引路径访问正确的数据项。

【讨论】:

    猜你喜欢
    • 2012-09-08
    • 2018-06-16
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2011-08-29
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多