以编程方式创建 uicollectionview 时使用自定义 init 方法 [英] Use custom init method when programmatically creating a uicollectionview

查看:23
本文介绍了以编程方式创建 uicollectionview 时使用自定义 init 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 Storyboard 的限制,我正在以编程方式创建 UICollectionView.这一切正常,当我想添加 UICollectionViewCell 时,我执行以下操作:

Due to the limitations of Storyboard I am creating a UICollectionView programmatically. This is working all fine and when I want to add a UICollectionViewCell I do the following:

[collectionView registerClass:[Cell class] forCellWithReuseIdentifier:@"ID"];

我想知道的是如何使用Cell"类中的自定义 init 方法,因为我无法执行以下操作:

What I was wondering is how can I use a custom init method from the class "Cell", because I can't do something like the following:

[collectionView registerClass:[[Cell class]init_custom]forCellWithReuseIdentifier:@"ID"];

问题:如何使用自定义 UICollectionViewCell 类中的自定义 init 方法?

Question: How can I use a custom init method from a custom UICollectionViewCell class?

推荐答案

如果我理解正确,那么我将创建您的集合视图单元格的子类.

If I understand you correctly, then I would create subclasses of your collection view cell.

首先用你想要的一切设置你的单元.

First setup your cell with everything you want.

@interface MyCollectionViewCell : UICollectionViewCell
// Your custom cell
@end

@implementation MyCollectionViewCell
// Your custom cell
@end

然后为每个集合视图创建一个只覆盖 init 的子类.

Then for each collection view create a subclass which only overrides init.

@interface MyCollectionViewCellForCollectionView1 : MyCollectionViewCell

@end

@implementation MyCollectionViewCellForCollectionView1
- (instancetype)init // Only override -init
{
    self = [super init];
    if (self) {
        // Setup for collection view one
    }
    return self;
}
@end

@interface MyCollectionViewCellForCollectionView2 : MyCollectionViewCell

@end

@implementation MyCollectionViewCellForCollectionView2
- (instancetype)init // Only override -init
{
    self = [super init];
    if (self) {
        // Setup for collection view two
    }
    return self;
}
@end

然后为每个不同的集合视图注册一个子类.

Then for each different collection view, you register one of your subclasses.

[collectionView1 registerClass:[MyCollectionViewCellForCollectionView1 class] forCellWithReuseIdentifier:@"ID"];
[collectionView2 registerClass:[MyCollectionViewCellForCollectionView2 class] forCellWithReuseIdentifier:@"ID"];

这将为您提供您希望的单独的自定义 init 方法,但请确保将所有功能保留在基类中.

This will get you the separate custom init methods you wish, but be sure to keep all your functionality in the base class.

这篇关于以编程方式创建 uicollectionview 时使用自定义 init 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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