编程创build一个uicollectionview时使用自定义的init方法

由于故事板的限制,我正在编程创build一个UICollectionView。 这工作都很好,当我想添加一个UICollectionViewCell我做到以下几点:

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

我想知道的是如何使用类“Cell”中的自定义init方法,因为我不能做如下的事情:

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

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

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

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

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

然后为每个集合视图创build一个只覆盖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 

然后为每个不同的收集视图,你注册你的一个子类。

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

这将为您提供您所希望的单独的自定义init方法,但一定要将所有function保留在基类中。