Как построить кнопку для индивидуального управления таймером и отображения обратного отсчета на этикетке? - PullRequest
0 голосов
/ 08 июня 2018

Я только что изучил Swift 4 месяца назад, и я застрял в проблеме, но я не знаю, как ее исправить.Я смотрел много учебных пособий по StackOverflow, Youtube и Medium, но не могу найти достойного решения.

Мой проект: В ViewController есть TableView, и у каждого tableViewCell есть timerLabel, timerNameLabel, playButton и stopButton,Когда я нажимаю кнопку воспроизведения, timeLabel ячейки начинает обратный отсчет.Когда я нажимаю stopButton, таймер останавливается.

Я знаю, как построить правильный таймер и правильный просмотр таблицы:

viewController:

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



    var myTimerList = CustomTimerList()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myTimerList.timerList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TimerTableViewCell
        return cell
    }

}

TimerTableViewCell:

import UIKit

class TimerTableViewCell: UITableViewCell {

    var timer = Timer()

    @IBOutlet weak var timerName: UILabel!
    @IBOutlet weak var secondLeftLabel: UILabel!
    @IBAction func stopButton(_ sender: UIButton) {

        timer.invalidate()

    }

    @IBAction func playButton(_ sender: UIButton) {

        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(updateTimer)), userInfo: nil, repeats: true)

    }

    @objc func updateTimer() {



    }

}

TimerClass:

import Foundation

class TimerClass {


    let timerSecond : Int
    let timerName : String

    init(second:Int, name:String) {


        timerSecond = second
        timerName = name

    }

}

TimerList:

import Foundation

class CustomTimerList {

    var timerList = [TimerClass]()

    init() {

        let customTimer = TimerClass(second: 100, name: "AAA")
        timerList.append(customTimer)
        timerList.append(TimerClass(second: 200, name: "BBB"))
        timerList.append(TimerClass(second: 400, name: "CCC"))
        timerList.append(TimerClass(second: 150, name: "DDD"))
        timerList.append(TimerClass(second: 800, name: "EEE"))
        timerList.append(TimerClass(second: 1000, name: "FFF"))

    }

}

, но мои проблемы:

1. Я пытался поместить runTimer в tableViewCell иЯ связал свой playButton с tableViewCell.swift в качестве IBAction.Внутри этой кнопки находится runTimer, но как мне получить данные из TimerList и показать обратный отсчет в timerLabel, , потому что я не могу получить indexPath.row.

2Я пытался поместить runTimer в viewController, чтобы runTimer мог получить indexPath.row, но у него есть другая проблема: как мне отобразить результат runTimer для timerLabel и сделать его обратным отсчетом, , потому что timerLabel был связан в tableViewCellвместо viewController.

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

вот оригинальный файл: https://app.box.com/s/0xviuay00pa2ief8b94ar5oh1002q3tn

1 Ответ

0 голосов
/ 08 июня 2018

Вам нужно установить cellForRowAt

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TimerTableViewCell

   let item = CustomTimerList.timerList[indexPath.row]
   cell.timerName.text = item.name
   cell.secondLeftLabel.text = "\(item.second)"

    return cell
}

//

struct CustomTimerList {

  static var timerList = [
      TimerClass(second: 100, name: "AAA"),
      TimerClass(second: 200, name: "BBB"),
      TimerClass(second: 400, name: "CCC"),
      TimerClass(second: 150, name: "DDD"),
      TimerClass(second: 800, name: "EEE"),
      TimerClass(second: 1000, name: "FFF")]

}

//

Вместо того, чтобы беспокоиться о текущем содержании меток обратного отсчетаи сохраните текущее значение, получите текущее значение из его текста и, если оно не равно нулю, уменьшите его и установите его обратно. Также не забывайте, что у вас нет механизма остановки для таймеров, если пользователь прокручивает это после этой строки вcellForRowAt

 let cell = tableView.dequeueReusableCell(withIdentifier: "customCell", for: indexPath) as! TimerTableViewCell
 cell.timer?.invalidate()

//

class TimerTableViewCell: UITableViewCell {
    var timer:Timer?
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...