我的问题很简单。我有一个包含 UICollectionView 的 UIViewController。在初始化我的单元格时,我为每个单元格添加了一个手势识别器,这样当你点击并按住它时,它会调用一个带有选择器的函数。
然后这个函数创建了一个我想要展示的 UIAlertController。 (基本上,你持有一个单元格,它会询问你是否要删除它,如果你说是,它会从 CollectionView 中删除它)
问题是我无法从我的 UICollectionView 中呈现 UIAlertController,因为它不是 ViewController。
我想以编程方式获取包含 UICollectionView 的 UIViewController,以从 UICollectionView 实现内部的函数显示此警报。
我通过在我的自定义中制定协议
UICollectionViewCell
并将这些事件委托给 UIViewController
,就像这样
在你的
MyCollectionViewCell
protocol MyCollectionViewCellDelegate: AnyObject {
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
使委托引用变弱以避免潜在的循环引用
weak var delegate: MyCollectionViewCellDelegate?
在要接收事件的视图控制器中采用新协议
class MyViewController:UIViewController, MyCollectionViewCellDelegate
编辑:如果你已经子类化了你的
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
会和以前一样