UICollectionCell调用CollectionViewController中的方法 [英] UICollectionCell to call method in CollectionViewController

查看:57
本文介绍了UICollectionCell调用CollectionViewController中的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标准的视图控制器,其中包含一个集合视图.

I have a standard view controller that contains a collection view.

我正在使用从 UICollectionViewCell 的自定义子类创建的自定义单元格填充集合视图.

I am populating the collection view with custom cells created from a custom subclass of UICollectionViewCell.

  1. 从集合视图单元格类中的集合视图类中调用方法的最佳实践是什么

  1. What is the best practice of calling a method in the collection view class from within the collection view cell class

为什么在我的集合视图单元格类中不调用以下init,我认为当collectionView类创建我的单元格时会调用此init.

Why doesnt the following init get called in my collection view cell class, I thought this would be called when the collectionView class creates my cells.

(id)initWithFrame:(CGRect)frame

我要执行此操作的原因是因为我要删除集合视图单元格,所以delete函数位于集合视图单元格类内部.我想在删除声音时播放声音,而宁愿在集合视图控制器类中初始化声音,而不是在每个单元格中初始化声音.

The reason I want to do this is because I am deleting a collection view cell, the delete function is inside the collection view cell class. I want to play a sound when it deletes, and would rather init the sound/s in the collection view controller class, and not for each cell.

推荐答案

默认情况下,UICollectionViewCell没有引用包含它的UICollectionView.因此,如果要从单元格与集合视图进行通信,则需要在单元格中添加属性或ivar.

By default, UICollectionViewCell has no reference to the UICollectionView that contains it. So if you want to communicate from the cell to the collection view, you need to add a property or ivar in the cell.

cell = [UICollectionViewCell ...];
cell.collectionView = self.collectionView;

第二,当从笔尖实例化一个UICollectionViewCell时,不调用initWithFrame:.调用initWithCoder:.您可以覆盖initWithCoder :(并调用super),或实现-awakeFromNib.

Second, when instantiating a UICollectionViewCell from a nib, initWithFrame: is not called; initWithCoder: is called instead. You can override initWithCoder: (and call super), or implement -awakeFromNib.

有时候我必须在一个类中实现两个init方法(例如initWithFrame:和initWithCoder:)时该怎么做,我每个实现都调用一个称为commonInit的方法

Sometimes what I do if I have to implement two init methods in one class (such as initWithFrame: and initWithCoder: ) is, I have each implementation call a single method called commonInit

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    } 
    return self;
}

- (id)initWithCoder:(NSCoder *)encoder
{
    self = [super initWithCoder:encoder];
    if (self) {
        [self commonInit];
    } 
    return self;
}

- (void)commonInit
{
// set up your instance
}

这消除了代码重复并提供了一致的行为.

This eliminates code duplication and provides consistent behavior.

参考: initWithFrame的UIView文档:

这篇关于UICollectionCell调用CollectionViewController中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆