从集合视图单元格执行Segue

时间:2016-03-10 00:53:47

标签: ios swift uicollectionview segue uicollectionviewcell

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)
}

}

我试图在用户点击我的集合视图中的一个单元格后执行Segue。似乎无法使用performSegueWithIdentifier执行此操作。 App Screenshot

3 个答案:

答案 0 :(得分:1)

performSegue无法提供实例方法UICollectionViewCell

由于UICollectionViewCell不是UIViewController,因此您无法使用performSegue(withIdentifier:sender:)。您可能更喜欢使用委托来通知您的父视图控制器,然后从那里performSegue

查看this answer的详细信息。问题略有不同,但解决方案的方式相同。

答案 1 :(得分:0)

您是否按照名称" showActionPreview"设置了segue标识符。此外,请确保您的segue从父视图控制器链接到故事板中的目标视图控制器。希望这会有所帮助。

答案 2 :(得分:0)

这是一个优雅的解决方案,只需要几行代码:

  1. 创建自定义UICollectionViewCell子类
  2. 使用情节提要,为按钮的“ Touch Up Inside ”事件定义IBAction
  3. 定义闭包
  4. 从IBAction调用闭包

快速4 + 代码

class MyCustomCell: UICollectionViewCell {

        static let reuseIdentifier = "MyCustomCell"

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

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

下一步,在

的闭包内部实现要执行的逻辑
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
    }

您也可以将这种方法用于表视图控制器。

相关问题