Search code examples
iosswiftxcodebuttoncollectionview

buttons not showing in collectionviewcell swift


I am trying to interact with a button that I embedded in a collectionviewcell. But it is not showing and I am not sure what is wrong with my code.

class Classic: UIViewController, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return 1
    }
    

   @IBOutlet var collectionView: UICollectionView!
   override func viewDidLoad()
     {
        // Register your cell
        let nib = UINib(nibName: "Subclass", bundle: nil)
        collectionView?.register(nib, forCellWithReuseIdentifier: "cell1")
   
     }
    
    // Collection view data source method
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
     
    // get your cell
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell1", for: indexPath) as! Subclass

      // here you will have access to your button
     cell.buttonOne.setTitle("2", for: .normal)
       
     // To handle tap on button
     cell.buttonOne.tag = indexPath.row
     cell.buttonOne.addTarget(self, action: #selector(didTapButton(sender:)), for: .touchUpInside)

    return cell
}

    @objc func didTapButton(sender: UIButton) {
        print("button tapped at index:-", sender.tag)
    }
     
}


class Subclass: UICollectionViewCell{
    @IBOutlet weak var buttonOne: UIButton!
    
}

and here is my storyboard enter image description here

As you can see in the image, I have put a button in the left-bottom cell, and the cell identifier is "cell1".

However, in the simulator enter image description here


Solution

  • The action syntax is wrong.

    Change addTarget(_:action:for:) to

    cell.buttonOne.addTarget(self, action: #selector(didTapButton), for: .touchUpInside)
    

    and the corresponding method to

    @objc func didTapButton(_ sender: UIButton) {