при нажатии кнопки у меня выходит ошибка
вот ошибка
Thread 1: Exception: "unable to dequeue a cell with identifier carCell
- must register a nib or a class for the identifier or connect a prototype cell in a storyboard"
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lappedTimes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath)
cell.textLabel?.text = lappedTimes[indexPath.row]
return cell
}
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var goal: UIButton!
@IBOutlet weak var trick: UIButton!
@IBOutlet weak var fail: UIButton!
@IBOutlet weak var other: UIButton!
@IBOutlet weak var tableView: UITableView!
var lappedTimes:[String] = []
private var timer: Timer!
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
super.viewDidLoad()
// Do any additional setup after loading the view.
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(countSeconds(_:)),
userInfo: nil,
repeats: true)
}
@objc func countSeconds(_ sender: Timer) {
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
let hourString = String(hour)
let minutesString = String(minutes)
let secondsString = String(seconds)
DispatchQueue.main.async {
self.timeLabel.text = hourString + ":" + minutesString + ":" + secondsString
}
}
@IBAction func goal(_ sender: UIButton) {
let currentTime = "\(timeLabel.text!)"
lappedTimes.append(currentTime)
tableView.reloadData()
}
}
Ответы (1 шт):
Очень малопонятный вопрос, но тем не менее я попытаюсь дать хоть какой-то самодостаточный ответ. Вы добавляете действие при нажатие на кнопку:
@IBAction func buttonTapped(_ sender: UIButton)
{
...
}
так же кроме кнопки по логике у вас должен быть виджет списка с вашими данными. Для работы с списком вам нужно добавить такое классы в наследование:
class SomeController: UIViewController, UITableViewDelegate, UITableViewDataSource {
дальше в viewDidLoad() необходимо подвязать виджет списка к контроллеру:
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
}
предварительно при этом добавив outlet:
@IBOutlet weak var tableView: UITableView!
Это все я так понял вы и без меня знаете наверное) Вот ваши методы для поддержки списка:
// 1
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
// 2
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cars.count
}
// 3
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath)
cell.textLabel?.text = cars[indexPath.row]
return cell
}
Выше это просто пример. Дальше после того как вы добавляете в массив данные, вам нужно вызвать метод:
tableView.reloadData()
и список перестроиться уже с новыми данными:
@IBAction func goal(_ sender: UIButton) {
let currentTime = "\(secondLabel.text!)"
lappedTimes.append(currentTime)
tableView.reloadData()
}
Вот есть очень хороший пример который решает вашу проблему. Туториалы по работе со списками и видеоролик
UPDATE
У вас есть массив:
var lappedTimes:[String] = []
если я правильно понял, то вы в него складываете данные касательно вашего времени из секундомера, значит вы этот массив можете использовать в списке:
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return lappedTimes.count
}
загрузка данных и отображение:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "carCell", for: indexPath)
cell.textLabel?.text = lappedTimes[indexPath.row]
return cell
}