iosswiftsegueuicollectionviewcelluistoryboardsegue

The UICollectoinViewCell has no member of present (in order to present another view )?


I have created a class for the custom cell that I use for a collection view in my app . In this cell I have a button that I'd like to lead to another storyboard from the current one . So I tried to use present as follow :

let storyboard = UIStoryboard(name: "Main", bundle: nil)
            let cr = storyboard.instantiateViewController(withIdentifier: "test")
            self.present(cr, animated: true)

but there is a problem with sender which in this case is self. The error says UICollectionViewCell has no member of present which make sense. But then how can I achive my goal as I may need to use the same concept for segus in order to transfer information from one storyboard to another ?


Solution

  • The solution to your problem can fixed in that way

    In your custom CollectionViewCell add Button as IBOutlet i.e

    class CustomCollectionViewCell : UICollectionViewCell
    {
        @IBOutlet weak var btnDemo: UIButton!
        //Otherstuff
    }
    

    And in the ViewController that has the CollectionView add IBAction from the that UIButton on the CustomCell and in the CellForRowAtIndexPath you need to add tag to that button in order to identify which button you clicked i.e

    class ViewController : UIViewController
    {
        @IBAction func btnButtonPressed(_ sender: Any) 
        {         
            let currentBtn = sender as UIButton
        } 
        func collectionView(collectionView: UICollectionView,
             cellForItemAtIndexPath indexPath: NSIndexPath) -> 
             UICollectionViewCell 
        {
           //Initialize Cell and other necessary stuff
           currentCell.btnDemo.tag = indexPath.row
        }