Search code examples
iosswiftuitableviewtimer

How to delete custom cell with timer in UITableView?


I'm developing an application that has a "Plus" button which can add stopwatch to a table view, every cell has its own timer, and can be played by itself.

When I'm trying to delete one cell like that, random issues are happening like:

  1. Order of the stopwatches being changed
  2. some stopwatches time is being zeroed .
  3. If trying to add new stopwatch after, an old stopwatch with it's timer are back!

TableView

class StopWatchViewController: UIViewController {
    @IBOutlet weak var stopWatchesTableView: UITableView!
    var stopwatchesList: [String] = []

    var stopwatchesNum : Int = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        stopWatchesTableView.delegate = self
        stopWatchesTableView.dataSource = self

        NotificationCenter.default.addObserver(self, 
                                               selector: #selector(applicationDidEnterBackground(noti:)),                        
                                               name: UIApplication.didEnterBackgroundNotification,
                                               object: nil)
    }

    @objc func applicationDidEnterBackground(noti: Notification) {
        // Save Date
        let shared  = UserDefaults.standard
        shared.set(Date(), forKey: "SavedTime")
        print(Date())
    }

    func refresh() {
        stopWatchesTableView.reloadData()
    }

    @IBAction func AddStopWatch(_ sender: Any) {
        stopwatchesNum += 1;
        stopwatchesList.append(String(format: "Stopwatch %d", stopwatchesNum))
        refresh()
    }
}

extension StopWatchViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return stopwatchesList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let stopWatch = stopwatchesList[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "StopwatchCell") as! StopWatchCell
        cell.initCell(title: stopWatch, index: indexPath.row)
        return cell
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == UITableViewCell.EditingStyle.delete {
            stopwatchesList.remove(at: indexPath.row)
            stopWatchesTableView.deleteRows(at: [indexPath], with: .automatic)
            refresh()
        }
    }
}

What can cause such issues ?


Solution

  • Don't call refresh method after deleting the row.Hope this help.