栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

访问UICollectionView的父UIViewController

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

访问UICollectionView的父UIViewController

我通过在自定义协议中制定协议来完成此任务

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的引用的最佳实践,但是我做的非常相似,请告诉我您的情况。


编辑: 如果您已经将您的子类化,

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
会和以前一样



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/613988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号