gpt4 book ai didi

ios - 访问 UICollectionView 的父 UIViewController

转载 作者:搜寻专家 更新时间:2023-10-30 21:55:04 24 4
gpt4 key购买 nike

我的问题很简单。我有一个包含 UICollectionView 的 UIViewController。在初始化我的单元格时,我为每个单元格添加了一个手势识别器,这样当你点击并按住它时,它会调用一个带有选择器的函数。

此函数然后创建一个我想要呈现的 UIAlertController。 (基本上,你持有一个单元格,它会询问你是否要删除它,如果你说是,它会从 CollectionView 中删除它)

问题是我无法从我的 UICollectionView 中呈现 UIAlertController,因为它不是 ViewController。

我想以编程方式获取包含 UICollectionView 的 UIViewController,以从 UICollectionView 实现内部的函数显示此警报。

最佳答案

我通过在我的自定义 UICollectionViewCell 中制定一个协议(protocol)并将这些事件委托(delegate)回 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
}

}

要记住的重要一点是为每个单元格设置委托(delegate)

cell.delegate = self

并在要接收事件的 View Controller 中采用新协议(protocol)

类 MyViewController:UIViewController, MyCollectionViewCellDelegate

我没有测试过这段代码,我不确定像这样在每个单元格中存储对 viewController 的引用的最佳做法,但我做了一些非常相似的事情,请告诉我你的进展情况。


编辑:如果您对UICollectionView 进行了子类化,则将其传递给 View Controller 的引用,以便您可以像这样使用它。

您的 MyViewController 现在看起来像这样

class MyViewController:UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
let collectionView = MyCollectionView()
collectionView.viewController = self
self.view.addSubview(collectionView)
}

}

以及您的自定义 Collection View 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 会和以前一样

关于ios - 访问 UICollectionView 的父 UIViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com