Search code examples
swiftuitableviewuicollectionviewdelegatesprotocols

TableView found nil in Collectionview cell Swift


Im trying to implement a solution that requires to have a TableView nested in a CollectionView Cell. For some reason then the table view is initialised, it is found as nil. That action is done from within the CollectionView Cell class.

This is the code snippet with the relevant functions:

class MNMessgesCollectionViewCell: UICollectionViewCell, UITableViewDataSource, UITableViewDelegate{


    @IBOutlet weak var _tableView: UITableView!


    var _messages : [MedNegMessage]?

    override func awakeFromNib() {
        super.awakeFromNib()

        // Initialization code
    }

    func setUpViews() {
        _tableView.delegate = self
        _tableView.dataSource = self
         _tableView.register(UINib(nibName: "MessageMNcell", bundle: nil), forCellReuseIdentifier: "messageCell")
    }

    func setUpCell(message: [MedNegMessage])
    {
         _messages = message

    }


} 


class  DashboardViewController: UICollectionViewDelegate, UICollectionViewDataSource{

     func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

          _collectionView.register(MNMessgesCollectionViewCell.self, forCellWithReuseIdentifier: "MNmessages")
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MNmessages", 
for: indexPath) as? MNMessgesCollectionViewCell 
else { return UICollectionViewCell()}

             cell.setUpViews()
             cell.setUpCell(message: self.messagesMN[indexPath.row])

             return cell

}

}


Error is always thrown at _tableView.delegate = self

Unexpectedly found nil while implicitly unwrapping an Optional value

Any advice?


Solution

  • 1)I guess you have just declared the tableView but not wired to the story board.

    2)Make sure class all Outlets are correct.