【问题标题】:How to tell when a UITableViewCell has been dequeued?如何判断 UITableViewCell 何时出队?
【发布时间】:2021-12-09 11:18:48
【问题描述】:

我有一个UITableViewCell,在那个单元格中,我设置了一个计时器,用当前时间更新单元格中的标签。所以每秒都会触发这个计时器,并更新这个标签。 但是当用户滚动通过这个单元格时,或者单元格不在屏幕上时,我觉得我应该停止计时器;更新当前未正确显示的标签没有用吗?

有什么方法可以检查一个单元格是否在屏幕上?还是没有出队?

这里有一些代码,你会喜欢的:

class TeamBattleTableViewCell: UITableViewCell {    
    @IBOutlet weak var resultsSubtitleLabel: MantisLabel!
    var timer = Timer()
    func updateDisplay() {
        ...
        updateTime()
        timer.invalidate()
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
    
    @objc func updateTime() {
        /*
        if self.is_dequeud {
            timer.invalidate()
        }
        */
        let man = TeamBattleManager.get()
        let d = man.end_date.offsetFrom(date: Date())
        resultsSubtitleLabel.text = d+" remaining"
    }   
}

【问题讨论】:

  • didEndDisplaying 在您的情况下还不够吗? developer.apple.com/documentation/uikit/uitableviewdelegate/…
  • 这正是我想要的。当将模态推入堆栈或通过 UITabViewController 切换到不同的选项卡时,它不会触发,但我真的没想到会这样。
  • 单元格中的计时器不是一个好方法。您的视图控制器中应该有一个计时器,当它触发时,迭代可见单元格并刷新它们。您可能还希望计时器的运行速度快于 1 秒。 Timer 不是很准确,因为它是截止日期计时器,不是真正的时间表,而且非常紧张。如果您以 0.2 秒的时间运行计时器,您的 UI 更新会更顺畅。此外,您的单元不应该了解模型。这只是一种看法。所以TeamBattleManager.get()违反了关注点分离原则。

标签: ios swift uitableview


【解决方案1】:

我认为你应该在 prepareForReuse() 中停止计时器

  override func prepareForReuse() {
    super.prepareForReuse()
    timer.invalidate()
  }

关于第二种情况(当显示一些模态屏幕时) - 你应该在你的视图控制器中处理它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2011-02-03
    • 2018-08-24
    • 2013-11-07
    相关资源
    最近更新 更多