问题
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:
- Create a custom UICollectionViewCell subclass
- Using storyboards, define an IBAction for the "Touch Up Inside" event of your button
- Define a closure
- 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