4thSpace
4thSpace

Reputation: 44312

Why doesn't tableview delegate work?

I have the following class in a singleview app. In IB, I have connected the datasource and datadelegate to the tableview. Is there something I'm doing wrong that none of the tableview delegates fire?

The cell identifier is set in IB.

import UIKit

class ViewController: UITableViewController {

    let myarray = ["item 1", "item 2", "item 3", "item 4"]
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell:UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "test")
        cell.textLabel?.text = myarray[indexPath.item]
        return cell;
    }


    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }

}

There is already a prototype cell in IB.

One other thing, viewDidLoad() doesn't even fire.

Upvotes: 0

Views: 89

Answers (1)

Josh Gafni
Josh Gafni

Reputation: 2881

You are supposed to dequeue cells in cellForRowAtIndexPath. In storyboard, add a UITableViewCell to the table if there isn't one already, and you should see a prototype cell. Make sure that the identifier of the prototype is "test" like it is in your code.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("test") as UITableViewCell

    cell.textLabel?.text = self.myarray[indexPath.row]

    return cell
}

Upvotes: 1

Related Questions