5

I have a UIViewController with a UICollectionView created inside it programmatically. I want to add a button to the cell:

viewDidLoad:

UICollectionViewLayout *layout = [[UICollectionViewFlowLayout alloc]init];
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];

    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[EMCell class] forCellWithReuseIdentifier:@"Cell"];

    [self.view addSubview:_collectionView];

And then:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    EMCell *cell = (EMCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    cell.backgroundColor = [UIColor greenColor];

    UIButton *button = (UIButton *)[cell viewWithTag:200];
    [button setFrame:CGRectMake(10, 10, 50, 60)];
    [button setTitle:@"Button" forState:UIControlStateNormal];

    [button addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [cell addSubview:button];
    return cell;
}

What am I doing wrong?

Oscar Swanros
  • 19,767
  • 5
  • 32
  • 48
  • You're adding a button to the cell each time it is used. You do understand that cells get reused, right? Why don't you just add the button in your `EMCell` class's `init` method? – rob mayoff Jul 24 '13 at 21:08
  • @edtheprogrammerguy the button doesn't show up. – Oscar Swanros Jul 24 '13 at 21:08
  • 1
    Also, you should be adding the button as a subview of `cell.contentView`. – rob mayoff Jul 24 '13 at 21:08
  • @robmayoff — adding the button as a subView con contentView in the cell, and initializing the button in the cell init method solved my problem. Thanks a lot. – Oscar Swanros Jul 24 '13 at 21:17

1 Answers1

5

Add your button as a subview of cell.contentView. Also, don't create the button every time collectionView:cellForItemAtIndexPath: is called. You might be reusing an existing cell that already has a button. Better to add the button in your custom cell's init method instead. Then just hide the button when you don't need it.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848