我有一个自定义的 UICollectionViewCell,里面有一个按钮。当我点击按钮时,会在该子类中触发一个事件。然后我想在 UICollectionView 本身上触发一个事件,我可以在视图控制器中处理该事件。
伪代码:
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
}
}
理想情况下,我定义的事件将出现在界面生成器中的默认操作出口旁边,然后允许我将其拖动到我的视图控制器代码中以创建上述内容collectionView_cellUpdated
功能,类似于@IBInspectable
用于公开自定义属性。
有没有办法在原生 Swift 3 中实现这样的模式?或者如果没有,有什么库可以实现这一点吗?
我不完全理解你的问题,但从我得到的情况来看,你可以简单地使用closure
通过UIButton
点击事件返回UIViewController
.
Example:
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
}
}
如果您遇到任何问题,请告诉我。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)