Я только что изучил 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