I'm getting in this program stack or it stops to work

23 Views Asked by At

This is my program I'm beginner the build succeeded but the running stop.

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet var textField: UITextField!

    var items = [String]()

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func addButton(sender: UIButton) {
        let newItem = textField.text
        items.append(newItem!)

        textField.resignFirstResponder()
    }

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

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier("Cell",forIndexPath: indexPath)

        cell.textLabel?.text = items[indexPath.row]
        cell.textLabel?.textColor = UIColor.redColor()

        return cell
    }
}

The build succeeds, on the running I get error in stack over flow showing 0 or nil Can you help?

1

There are 1 best solutions below

1
Zac Kwan On BEST ANSWER

i think you are missing a tableView.reloadData() after adding newItem to your datasource

Try adding it in your IBAction like this

@IBAction func addButton(sender: UIButton) {

  let newItem = textField.text
  items.append(newItem!)
  tableView.reloadData()
  textField.resignFirstResponder()

}