Adding UIButton Programs to a UICollectionView Cell Programmatically

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?

+4
source share
1 answer

Add your button as a subheading of cell.contentView . Also, do not create a button every time collectionView:cellForItemAtIndexPath: called. Perhaps you are reusing an existing cell that already has a button. It is better to add a button to your own init method. Then just hide the button when you don’t need it.

+5
source

Source: https://habr.com/ru/post/1493286/


All Articles