class MyViewController: BaseViewController {
var dispalyingCellArray = [UITableViewCell]()
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let nib0 = UINib(nibName: "MyCell0", bundle: nil)
tableView.register(nib0, forCellReuseIdentifier: "MyCell0ID")
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 360.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//启动定时器
setupTimer()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
//关闭定时器
destroyTimer()
}
func destroyTimer() {
if timer != nil {
if timer!.isValid {
timer?.invalidate()
}
timer = nil
}
}
func setupTimer() {
destroyTimer()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerRepeats), userInfo: nil, repeats: true)
}
@objc func timerRepeats() {
for encell in dispalyingCellArray {//遍历当前显示的cell数组,每个cell都进行刷新
if let cell0 = encell as? MyCell0 {
cell0.refreshTime()
}
}
}
}
extension MyViewController: UITableViewDataSource, UITableViewDelegate {
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell0ID") as! MyCell0
return cell
}
//通过下面两步,可以维持一个仅包含当前显示的cell的数组,timer中遍历该数组,刷新所有的(当前显示的)cell!
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
dispalyingCellArray.append(cell) //保存当前显示的cell到数组
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if let index = dispalyingCellArray.index(of: cell) {
dispalyingCellArray.remove(at: index)//把被滚出屏幕的cell移除
}
}
}