从 UICollectionViewCell 传播自定义事件 [英] Propagate a custom event from a UICollectionViewCell

查看:26
本文介绍了从 UICollectionViewCell 传播自定义事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 UICollectionViewCell,里面有一个按钮.当我点击按钮时,会在该子类中触发一个事件.然后我想在 UICollectionView 本身上触发一个事件,我可以在我的视图控制器中处理.

I have a custom UICollectionViewCell with a button inside it. When I tap the button, an event is fired inside that subclass. I want to then trigger an event on the UICollectionView itself, which I can handle in my view controller.

伪代码:

class MyCell : UICollectionViewCell {
    @IBAction func myButton_touchUpInside(_ sender: UIButton) {
        // Do stuff, then propagate an event to the UICollectionView
        Event.fire("cellUpdated")
    }
}

class MyViewController : UIViewController {
    @IBAction func collectionView_cellUpdated(_ sender: UICollectionView) {
        // Update stuff in the view controller 
        // to reflect changes made in the collection view
    }
}

理想情况下,我定义的事件将出现在 Interface Builder 中的默认操作出口旁边,然后允许我将其拖到我的视图控制器代码中以创建上述 collectionView_cellUpdated 函数,类似于 collectionView_cellUpdatedcode>@IBInspectable 用于暴露自定义属性.

Ideally, the event I define would appear alongside the default action outlets in the Interface Builder, allowing me to then drag it into my view controller code to create the above collectionView_cellUpdated function, similar to how @IBInspectable works in exposing custom properties.

有没有办法在原生 Swift 3 中实现这样的模式?或者,如果没有,任何使之成为可能的库?

Is there any way to implement a pattern like this in native Swift 3? Or if not, any libraries that make it possible?

推荐答案

我不完全理解你的问题,但从我得到的信息来看,你可以简单地使用 closure 来传递 UIButton 点击事件返回到 UIViewController.

I don't understand your question completely but from what I got, you can simply use a closure to pass the UIButton tap event back to the UIViewController.

示例:

1.自定义 UICollectionViewCell

class MyCell: UICollectionViewCell
{
    var tapHandler: (()->())?

    @IBAction func myButton_touchUpInside(_ sender: UIButton)
    {
        tapHandler?()
    }
}

2.MyViewController

class MyViewController: UIViewController, UICollectionViewDataSource
{
    //YOUR CODE..

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCell
        cell.tapHandler = {
            //Here you can do your custom handling
        }
        return cell
    }
}

如果您遇到任何问题,请告诉我.

Let me know if you face any issues.

这篇关于从 UICollectionViewCell 传播自定义事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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