Mbusi Hlatshwayo
Mbusi Hlatshwayo

Reputation: 554

Displaying text in a table view

I am trying to figure out why this code will not add any text to the cells in the table. I checked and the array is being filled with text when the button is pressed but nothing shows up in the cell.

class ViewController: UIViewController, UITableViewDelegate {

    var names: [String] = []

    @IBOutlet var nameTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        NSUserDefaults.standardUserDefaults().setObject("Mbusi", forKey: "name")
        var name = NSUserDefaults.standardUserDefaults().objectForKey("name")! as String
        println(name)
        NSUserDefaults.standardUserDefaults().setObject(names, forKey: "Users")
        var users = NSUserDefaults.standardUserDefaults().objectForKey("Users")! as [String]


    }

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        self.view.endEditing(true)
    }

    @IBAction func addNameToList(sender: AnyObject) {

        var index = 0
        var namesText = nameTextField.text

        names.append(namesText)
        println(names)


        func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            let cell  = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")

            cell.textLabel?.text = names[indexPath.row]

            return cell

        }


    }

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


}

Upvotes: 0

Views: 60

Answers (1)

Stefan Arentz
Stefan Arentz

Reputation: 34945

Two things:

You need to move

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

outside addNameToList into your ViewController.

And second, you need to call tableView.reloadData() after you add items to your names array.

Upvotes: 2

Related Questions