初始化自定义UICollectionViewCell

Ber*_*tie 4 ipad ios uicollectionview uicollectionviewcell

我有一个自UICollectionViewCell定义背景视图,使用多种颜色方案之一绘制.背景视图的颜色方案在我-(id)initWithFrame:andColourPalette:的View 自定义初始化程序中设置.

我的UICustomViewCell子类中有一个类似的自定义初始化器,但是当我在设置单元格时,我无法弄清楚如何调用此初始化器cellForItemAtIndexPath:

任何人都可以帮我这样做吗?或者提供替代解决方案,将此色彩词典传递到Cell中以传递给subView?

编辑以显示更多细节:

这是我在UICollectionView VC中的内容:

在ViewWillAppear中:

[self.collectionView registerClass:[OPOLawCollectionViewCell class] forCellWithReuseIdentifier:CELL_ID];
self.colourPalette = [OPOColourPalette greenyColourPalette];
Run Code Online (Sandbox Code Playgroud)

在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;
Run Code Online (Sandbox Code Playgroud)

在我的自定义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];
Run Code Online (Sandbox Code Playgroud)

但这不起作用 - 我猜是因为没有设置属性.

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

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

所以我想我需要在这里使用自定义的intialiser,但我无法弄清楚如何调用它,或者从哪里...

谢谢

Tal*_*ala 12

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

[self.collectionView_ registerClass:[YourCustomClass class]
        forCellWithReuseIdentifier:@"CustomCell"];
Run Code Online (Sandbox Code Playgroud)

然后在你的方法中cellForItemAtIndexPath:

 YourCustomClass *cell = (YourCustomClass *)[collectionView 
         dequeueReusableCellWithReuseIdentifier:@"CustomCell" forIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

这样做是因为collectionView可能有1000个单元格,10个可见.在可能的情况下,您不会将所有这些内容初始化并重用.

编辑

您应该colorPaletter在释放可重复使用的单元格后进行设置.可以把它想象成一个可以容纳任何颜色的容器.您需要确定(通过索引路径)要绘制的颜色.