【问题标题】:Perform Segue from Collection View Cell从集合视图单元执行 Segue
【发布时间】:2016-03-10 00:53:46
【问题描述】:
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

【问题讨论】:

  • 你没有描述问题。它崩溃了吗? ActionViewController 是什么?是类还是实例?
  • 使用 UICollectionViewDelegate 协议中指定的 collectionView(didSelectItemAtIndexPath:) 方法,而不是单元格中的操作,除非您需要每个单元格具有不同操作的多个按钮。
  • 你解决了吗?我有同样的问题,选择项目对我不起作用,因为我在单元格内有 Cell + 一个按钮,这个按钮的作用与按下单元格不同。

标签: ios swift uicollectionview segue uicollectionviewcell


【解决方案1】:

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

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

您也可以将此方法与表视图控制器一起使用。

【讨论】:

    【解决方案2】:

    实例方法 performSegue 不适用于 UICollectionViewCell

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

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

    【讨论】:

      【解决方案3】:

      您是否通过完全命名为“showActionPreview”的方式设置了转场标识符。此外,确保您的 segue 从您的父视图控制器链接到情节提要中的目标视图控制器。希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多