-1

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
otter
  • 93
  • 2
  • 8
  • Where do you have that code? If that label is in every cell, then I would suggest putting the code in the init method for a custom cell, (or do it in IB) not in cellForItemAtIndexPath (if that's where you're doing this). – rdelmar Mar 15 '15 at 17:34
  • Sorry, i forgot to mention that. This code is in cellForItemAtIndexPath method. – otter Mar 15 '15 at 17:38

3 Answers3

2

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.

rdelmar
  • 103,982
  • 12
  • 207
  • 218
0

Delete and add the label in cellForItemAtIndexPath. First ull check if label is in the cell, if yes, remove it from superview, then create new label and add it to its contentview.

IxPaka
  • 1,990
  • 1
  • 16
  • 18
  • I tried that, but that is not the problem. The label is releases automatically after new load. – otter Mar 15 '15 at 17:39
0

Probably, you allocate your uilabel in cellForRowAtIndexPath method and it appears again and again when you reload your collectionView. To solve your problem,just define your label as a property and allocate it in the viewDidLoad method and do what you want in cellForRowAtIndexPath method. Hope this will help.

For example, this is your header file:

@property (retain,nonatomic) IBOutlet UILabel *label;

and this is the viewDidLoad method of implemantation file:

    _label = [[UILabel alloc] init];
miletliyusuf
  • 982
  • 1
  • 10
  • 12