Search code examples
iosswiftuitableviewreloaddata

How do I reload data in my TableView


I've seen some answers on Stack about this question but a lot of them are from 5 years ago and using an older version of Swift. I would like to reload the data in the table every time the user hits save so that the appended event will now be added to the table. But no matter what I seem to do nothing is showing up! I've tried adding table.reloadData() in my save function. But i get an error for:

Thread 1 error, Fatal error: unexpectedly found a nil while unwrapping an optional value.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var txtTitle: UITextField!
    @IBOutlet weak var txtLocation: UITextField!
    @IBOutlet weak var txtDate: UITextField!
    @IBOutlet weak var txtTime: UITextField!

    var eventsArray = [Event]()

    @IBAction func btnSave() {
        let event = Event(tits: txtTitle.text!, locs: txtLocation.text!)

        eventsArray.append(event)
        table.reloadData()
        print(eventsArray)

    }

    @IBOutlet weak var table: UITableView!

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

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

        cell.title.text = eventsArray[indexPath.row].title
        cell.location.text = eventsArray[indexPath.row].location

        return cell
    }
}

Solution

  • Did you set tableView's delegate on viewDidLoad?

    table.delegate = self