从集合视图单元执行 Segue [英] Perform Segue from Collection View Cell

查看:23
本文介绍了从集合视图单元执行 Segue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 似乎无法做到这一点.应用截图

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

推荐答案

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

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

  1. 创建自定义 UICollectionViewCell 子类
  2. 使用故事板,为按钮的Touch Up Inside"事件定义一个 IBAction
  3. 定义一个闭包
  4. 从 IBAction 调用闭包
  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+ 代码

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
    }

您也可以将此方法用于表视图控制器.

You can use this approach also with table view controllers.

这篇关于从集合视图单元执行 Segue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆