user8748833
user8748833

Reputation:

Swift - Could not cast value of 'UITableViewCell'

I am attempting to create a very simple Table View containing images and labels. I am attempting to customize/style what the inside of each cell looks like (programattically), therefore I have created a class called "BarCell" in order to program how each cell should look. However, when I try to follow this format, I am getting the following error :

Could not cast value of type 'UITableViewCell' (0x10bda7038) to 'ProjectName.BarCell' (0x105332c38).

What does this error mean? I have declared my class of BarCell as a type of UITableViewCell. Therefore, how am I getting this error? Very new to swift, so any tips advise that could point me to the right direction will be extremely helpful. Here is my complete code

//
//  HomeController.swift
//  Covered
//
//  Created by name on 1/3/18.
//  Copyright © 2018 name. All rights reserved.
//

import UIKit
import Firebase

class HomeController: UIViewController, UITableViewDelegate, UITableViewDataSource{

    let bars = ["one", "two", "three"]

    let tableView: UITableView = {
        let tv = UITableView()
        tv.separatorStyle = .none
        tv.allowsSelection = true
        return tv
    }()

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

    var barImage: UIImage?
    var barCover: String?

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell


        cell.imageView?.image = UIImage(named: bars[indexPath.row])
        cell.textLabel?.text = bars[indexPath.item]

        barImage = cell.imageView?.image
        barCover = cell.textLabel?.text
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 160
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpNavigationBar()
        setUpTableView()

        //user is not logged in

        if Auth.auth().currentUser?.uid == nil {
            perform(#selector(handleSignOut), with: nil, afterDelay: 0)
        }
    }

    func setUpNavigationBar(){
        navigationItem.title = "Covered"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
        navigationItem.leftBarButtonItem?.tintColor = .black
    }
    func setUpTableView(){
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

        view.addSubview(tableView)
        _ = tableView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: view.frame.width, heightConstant: view.frame.height)
    }
    @objc func handleSignOut(){

        do{
            try Auth.auth().signOut()
        } catch let logOutError{
            print("Here is the log out error: /n")
            print(logOutError)
        }

        //change state of user default
        UserDefaults.standard.setIsLoggedIn(value: false)

        //present login controller
        let loginController = LoginController()
        present(loginController, animated: true, completion: nil)
    }

}

class BarCell: UITableViewCell{
    let cellView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.dropShadow()
        return view
    }()

    override init(style: UITableViewCellStyle, reuseIdentifier: String?){
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
    }

    func setup(){
        addSubview(cellView)
        _ = cellView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 4, leftConstant: 8, bottomConstant: 4, rightConstant: 8)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

My error is coming up at line 32, which is :

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell

Any ideas why this is happening? My code runs well when i cast this line as! UITableViewCell directly. However, I am trying to do this in order to set the appearance for each cell. Thanks in advance for any advice.

Upvotes: 2

Views: 758

Answers (1)

rmaddy
rmaddy

Reputation: 318804

The problem is that the lines:

tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

and

let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! BarCell

don't match.

If you really want the cell to have a type of BarCell then register a BarCell instead of s UITableViewCell.

tableView.register(BarCell.self, forCellReuseIdentifier: "cell")

Upvotes: 7

Related Questions