Perform Segue from Collection View Cell

牧云@^-^@ 提交于 2019-12-12 16:50:54

问题


import UIKit

class ActionCollectionViewCell: UICollectionViewCell {
     @IBOutlet weak var myLabel: UILabel!
     @IBOutlet weak var actionGIF: UIImageView!

     @IBAction func actionPressed(sender: AnyObject) {
         print(myLabel.text)
         Global.actionButtonIndex = myLabel.text!.toInt()! - 1
         print(actionGIF.image)
         ActionViewController.performSegueWithIdentifier("showActionPreview", sender: nil)
}

}

I am trying to perform a Segue after User Clicking on One of the Cell in my Collection View. Can't seem to do that using performSegueWithIdentifier. App Screenshot


回答1:


Here's an elegant solution that only requires a few lines of code:

  1. Create a custom UICollectionViewCell subclass
  2. Using storyboards, define an IBAction for the "Touch Up Inside" event of your button
  3. Define a closure
  4. Call the closure from the IBAction

Swift 4+ code

class MyCustomCell: UICollectionViewCell {

        static let reuseIdentifier = "MyCustomCell"

        @IBAction func onAddToCartPressed(_ sender: Any) {
            addButtonTapAction?()
        }

        var addButtonTapAction : (()->())?
    }

Next, implement the logic you want to execute inside the closure in your

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCustomCell.reuseIdentifier, for: indexPath) as? MyCustomCell else {
            fatalError("Unexpected Index Path")
        }

        // Configure the cell
        // ...


        cell.addButtonTapAction = {
            // implement your logic here, e.g. call preformSegue()  
            self.performSegue(withIdentifier: "your segue", sender: self)              
        }

        return cell
    }

You can use this approach also with table view controllers.




回答2:


Instance method performSegue is not available from a UICollectionViewCell:

Since an UICollectionViewCell is not an UIViewController, you can not use performSegue(withIdentifier:sender:) from it. You may prefer use delegates to notify your parent view controller and then, performSegue from there.

Take a look at the details of this answer. The question is slightly different but the solution lies in the same pattern.




回答3:


Have you set the segue identifier by exactly named "showActionPreview". Moreover, ensure that your segue linked from your parent view controller to your destination view controller in storyboard. Hope this would be help.



来源:https://stackoverflow.com/questions/35905630/perform-segue-from-collection-view-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!