Search code examples
iosobjective-cuicollectionviewlayout

Allocating UILabel in UICollectionViewCell


I making app with collection view and different layout for portrait and landscape orientation and i am allocating UIlabel for every cell.

This is how i do it.

UILabel *scheduleCellLabel = [[UILabel alloc] init];
scheduleCellLabel.textAlignment = NSTextAlignmentCenter;
scheduleCellLabel.frame = CGRectMake(0, 0,scheduleCell.bounds.size.width, scheduleCell.bounds.size.height);
[scheduleCell addSubview:scheduleCellLabel];

Problem is that i reload collection view everytime the orientation changes, but the old cells stays in collection view. I tried to remove the label from cell on load, but that is not the issue.

This is how it looks:

enter image description here

Thanks in advance.


Solution

  • In my opinion, it's not good practice to put subview-adding code in cellForRowAtIndexPath unless you need to; for instance, if some cells have a subview, and some do not based on the indexPath. You should either make the cell in IB, or subclass the cell, and add any subviews in the cell's init method. That way, you don't have to remove views before you re-add them, or check if they exist before you add one; that just complicates your cellForRowAtIndexPath method.