KexAri
KexAri

Reputation: 3977

Unable to dequeue a cell

Having an issue with TableView like so:

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

        let cellReuseIdentifier = "cell"
        let cell: UITableViewCell = autoCompleteTableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as UITableViewCell
        let index = indexPath.row as Int

        cell.textLabel!.text = tableArray[index]

        return cell


    }

When I run the app I get: "unable to dequeue a cell with identifier cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard". What am I doing wrong here?

EDIT:

I'm not using the storyboard for this UITableView

Upvotes: 0

Views: 430

Answers (4)

Péter Kovács
Péter Kovács

Reputation: 280

You should use your original code, because it's much better solution than:

UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
   cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}

Only thing you need to do yet is registering your UITableViewCell class in viewDidLoad()

    self.autoCompleteTableView.registerClass(UITableViewCell.classForCoder(), forCellWithReuseIdentifier: "cell")

then just use your original code in cellForRow:

let cellReuseIdentifier = "cell"
let cell: UITableViewCell = autoCompleteTableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier, forIndexPath: indexPath) as UITableViewCell

Upvotes: 0

Luca D'Alberti
Luca D'Alberti

Reputation: 4849

In the viewDidLoad or wherever you want (you have to run it only once), you must register the identifier, also for UITableViewCell

autoCompleteTableView.registerClass(
    UITableViewCell.self,
    forCellReuseIdentifier: "cell"
)

Upvotes: 1

W.K.S
W.K.S

Reputation: 10095

If you're not using a storyboard, then you can create default UITableViewCell with your cellIdentifier:

UITableViewCell *cell =  [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell) {
   cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}

This code attempts to find a UITableViewCell with the given identifier. Failing to do so, it creates a new UITableViewCell with the given identifier and adds it to the UITableView.

Upvotes: 1

Buntylm
Buntylm

Reputation: 7373

Give the identifier of your custom cell. As per your code let cellReuseIdentifier = "cell" it should be cell

If you are not using Storyboard then you have to register your custom cell

[self.tableView registerClass: [CustomCell class] forCellReuseIdentifier:@"cell"];

enter image description here

Upvotes: 1

Related Questions