Как удалить пользовательскую ячейку с таймером в UITableView? - PullRequest
0 голосов
/ 25 января 2019

Я разрабатываю приложение, которое имеет кнопку «Плюс», которая может добавлять секундомер к представлению таблицы, каждая ячейка имеет свой таймер и может воспроизводиться сама по себе.

Когда я пытаюсьчтобы удалить одну ячейку, случайные проблемы происходят следующим образом:

  1. Порядок изменения секундомеров
  2. некоторые часы секундомеров обнуляются.
  3. При попыткедобавить новый секундомер после того, как старый секундомер с таймером вернулся!

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()
        }
    }
}

Что может вызвать такие проблемы?

1 Ответ

0 голосов
/ 25 января 2019

Не вызывайте метод обновления после удаления строки. Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...