Use custom init method when programmatically creating a uicollectionview

╄→гoц情女王★ 提交于 2019-12-11 02:51:47

问题


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"];

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"];

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


回答1:


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

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"];

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



来源:https://stackoverflow.com/questions/28252912/use-custom-init-method-when-programmaticly-creating-a-uicollectionview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!