我通过在我的自定义UICollectionViewCell 中创建一个协议并将这些事件委托给UIViewController 来做到这一点,就像这样
在你的MyCollectionViewCell
protocol MyCollectionViewCellDelegate: class {
func didLongPressCell()
}
class MyCollectionViewCell:UICollectionViewCell {
weak var delegate:MyCollectionViewCellDelegate?
func longPressAction() {
if let del = self.delegate {
del.didLongPressCell
}
}
}
然后回到你的MyViewController
class MyViewController:UIViewController, MyCollectionViewCellDelegate {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionViewCell
cell.delegate = self
return cell
}
func didLongPressCell() {
// do what you want with the event from the cell here
}
}
要记住的重要一点是为每个单元格设置委托
cell.delegate = self
并在您想要接收事件的视图控制器中采用您的新协议
class MyViewController:UIViewController, MyCollectionViewCellDelegate
我没有测试过这段代码,我不确定在每个单元格中存储对 viewController 的引用的最佳实践,但我做了一些非常相似的事情,让我知道你的进展情况。 em>
编辑:如果您已将 UICollectionView 子类化,则将其传递给视图控制器,以便您可以像这样使用它。
您的 MyViewController 现在看起来像这样
class MyViewController:UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let collectionView = MyCollectionView()
collectionView.viewController = self
self.view.addSubview(collectionView)
}
}
还有你的自定义集合视图MyCollectionView
class MyCollectionView:UICollectionView, MyCollectionViewCellDelegate {
weak var viewController:UIViewController?
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCollectionViewCell
cell.delegate = self
return cell
}
func didLongPressCell() {
if let vc = self.viewController {
// make use of the reference to the view controller here
}
}
}
UICollectionViewCell 与以前相同