David
David

Reputation: 839

Why can I not cast this cell to a class that inherits from cell in swift?

I am creating a TableView in swift using the UITableViewCOntroller, which I have done in several other apps, however this time when I try to cast my cell to the custom cell class I get the error that it cannot be cast.

Here is my code:

class CollapseNoteViewController: UITableViewController {

    let titleArray = ["Troy and Abed", "Shirly and Annie", "Pierce and Ben"]
    let noteArray = ["The best", "Pretty cool", "The worst"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return titleArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // This is where I get the error
        let cell = tableView.dequeueReusableCell(withIdentifier: K.reuseIdentifier, for: indexPath) as! NoteTableViewCell 
        
        cell.titleLabel?.text = titleArray[indexPath.row]
        cell.textLabel?.text = noteArray[indexPath.row]
        
        return cell
    }
    
}

class NoteTableViewCell: UITableViewCell {

    @IBOutlet weak var cardView: UIView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var mainTextLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
    }
    
}

The full error text:

Could not cast value of type 'UITableViewCell' (0x1eccdbb70) to 'CollapseANote.NoteTableViewCell' (0x104d3ced8).
Could not cast value of type 'UITableViewCell' (0x1eccdbb70) to 'CollapseANote.NoteTableViewCell' (0x104d3ced8).
2021-02-18 10:36:47.613801-0500 CollapseANote[639:74162] Could not cast value of type 'UITableViewCell' (0x1eccdbb70) to 'CollapseANote.NoteTableViewCell' (0x104d3ced8).

Where I set the class for the prototype cell:

enter image description here

Where I set the class for TableViewController:

enter image description here

Upvotes: 0

Views: 95

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

You nest to table cells and set the class name to the inner one that's why ist's not visible here

enter image description here

Drag the inner one to out like

enter image description here

Then delete the NoteItemCell

enter image description here

It's up to you to leave it if it represents another different cell

Upvotes: 1

Related Questions