Reputation:
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?
Upvotes: 2
Views: 3164
Reputation: 42598
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.
Upvotes: 2