mardi 1 décembre 2020

The delegate pattern does not fire in the class where it is implemented

There is a TopMenuBar class. This is a menu bar (collectionView) for a tableViewCell in the main class (named - MainVC).

class TopMenuBar: UITableViewCell {
     public var delegate: TopMenuBarDelegate?
}

and protocol:

protocol TopMenuBarDelegate {
     func didTapTopMenuCell(named: String)
}

In the didSelectItemAt() method with delegate, I call this protocol:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    
     ///Relay to delegate about menu item selection
    let selectedItem = menuItems[indexPath.row + 1].description
    delegate?.didTapTopMenuCell(named: selectedItem)
}

Further, in the main class - MainVC, I subscribed to the protocol - TopMenuBarDelegate, added a protocol method - didTapTopMenuCell(), created an instance of the TopMenuBar class and in the viewDidLoad method I assigned a delegate to this protocol - the MainVC class.

class MainVC: UIViewController, TopMenuBarDelegate {

   let topMenuBar = TopMenuBar()

   func didTapTopMenuCell(named: String) {
       print(named)
   }
   override func viewDidLoad() {
       super.viewDidLoad()
   topMenuBar.delegate = self
   }
}

To test the functionality, I only want to print the name of the cell that I clicked on. As a result, nothing appears in the console.

Aucun commentaire:

Enregistrer un commentaire