Initializing a custom UICollectionViewCell

Deadly 提交于 2019-12-05 18:50:22

Yuo have to register your customCells in collectionView:

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

And then in your method cellForItemAtIndexPath:

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

It is done because collectionView might have 1000 cells and 10 visible. You don't keep all of them initialized and reuse when possible.

EDIT

You should set colorPaletter after you deque the reusable cell. Think of it as a container which can hold any color. You need to determine (by indexpath) what color to paint.

Y.Muranaka

You shouldn't do below if your custom cell is in the Storyboard,

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

Because Storyboard take responsibility to register Cell_ID own. Now, It will conflict to be generated invalid Cell if you use both.

Way off, every answer. The questioner is looking for a way to uniquely identify each cell upon initialization, which happens prior to dequeuing a cell, and prior to a cell's access to its index path property.

The only way to do this is to assign a unique reuse identifier to every cell based on what the index path value will be (assuming you will know what that will be—and, in your case, you will); then, when dequeuing the cell, use the index path to find the cell with the corresponding reuse identifier.

Does this negates the purpose of reuse identifiers? Absolutely not. You'll be reusing that cell every time you need to use it again. Reuse identifiers were not meant to limit you to a cookie-cutter cell for every cell in your collection view; they are also intended to be "unique use" identifiers.

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