初始化一个自定义的UICollectionViewCell

我有一个自定义的UICollectionViewCell有一个自定义的背景视图,使用几种配色scheme之一绘制。 背景视图的颜色scheme是在我的自定义初始化程序-(id)initWithFrame:andColourPalette:设置的视图。

我在我的UICustomViewCell子类中有一个类似的自定义初始化,但我不知道如何调用这个初始化,当我在cellForItemAtIndexPath:设置单元格cellForItemAtIndexPath:

任何人都可以帮我做到这一点? 或者提供另一种解决scheme,将这个Dictionary的颜色传递给Cell传递给子视图?

编辑显示更多的细节:

这是我在我的UICollectionView VC:

在ViewWillAppear中:

 [self.collectionView registerClass:[OPOLawCollectionViewCell class] forCellWithReuseIdentifier:CELL_ID]; self.colourPalette = [OPOColourPalette greenyColourPalette]; 

在cellForItemAtIndexPath中:

 UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CELL_ID forIndexPath:indexPath]; OPOLawCollectionViewCell *lawCell = (OPOLawCollectionViewCell *)cell; MainLevel *level = self.collectionData[indexPath.row]; lawCell.delegate = self; lawCell.colourPalette = self.colourPalette; 

在我的自定义UICollectionViewCell中

 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // get background view OPOLawBook *lawBookView = [[OPOLawBook alloc]initWithFrame:CGRectMake(0, 0, 200, 265) andColourPalette:self.colourPalette]; 

但是这不起作用 – 我猜是因为房产没有成立。

如果我将最后一行更改为此,那么它工作正常:

  OPOLawBook *lawBookView = [[OPOLawBook alloc]initWithFrame:CGRectMake(0, 0, 200, 265) andColourPalette:[OPOColorPalette greenyColorPalette]]; 

所以我想我需要在这里使用一个自定义的intialiser,但我不知道如何调用它,或从哪里…

谢谢

Yuo必须在collectionView中注册您的customCells:

 [self.collectionView_ registerClass:[YourCustomClass class] forCellWithReuseIdentifier:@"CustomCell"]; 

然后在你的方法cellForItemAtIndexPath

  YourCustomClass *cell = (YourCustomClass *)[collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath]; 

这是因为collectionView可能有1000个单元,10个可见。 如果可能的话,你不要把它们全部保存起来并重新使用。

编辑

在您将可重用单元colorPaletter后,您应该设置colorPaletter 。 把它想象成一个可以容纳任何颜色的容器。 您需要确定(通过indexpath)要绘制的颜色。

如果您的自定义单元格位于Storyboard ,则不应在下面执行操作,

 [self.collectionView registerClass:[OPOLawCollectionViewCell class] forCellWithReuseIdentifier:CELL_ID]; 

因为Storyboard负责注册Cell_ID 。 现在,如果你同时使用两个单元格,将会产生无效单元格。

一路走,每一个答案。 提问者正在寻找一种在初始化时唯一标识每个单元的方法,在出现单元之前以及在单元访问其索引path属性之前。

唯一的方法就是根据索引path值是什么来为每个单元格分配一个唯一的重用标识符(假设你将知道这将是什么,在你的情况下,你会)。 那么当出列单元格时,使用索引path查找具有相应重用标识符的单元格。

这是否否定重用标识符的目的? 绝对不。 每次需要再次使用时,您都将重新使用该单元格。 重用标识符并不意味着将您限制为集合视图中每个单元格的切割单元格; 他们也打算成为“唯一使用”的标识符。