以编程方式创建 uicollectionview 时使用自定义 init 方法

Use custom init method when programmatically creating a uicollectionview

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

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

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

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

问题:如何使用来自自定义 UICollectionViewCell class 的自定义初始化方法?

如果我对你的理解正确,那么我会创建你的集合视图单元格的子classes。

首先用你想要的一切设置你的手机。

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

@implementation MyCollectionViewCell
// Your custom cell
@end

然后为每个集合视图创建一个仅覆盖 init.

的子class
@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

然后对于每个不同的集合视图,您注册一个子classes。

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

这将为您提供所需的单独的自定义初始化方法,但请务必将所有功能保留在基础 class。