Getting button action : UICollectionView Cell Getting button action : UICollectionView Cell ios ios

Getting button action : UICollectionView Cell


I had this problem as well. No subviews would receive touch events. While Scott K's workaround does work, I still felt something was wrong. So I took another look at my nib, and noticed that the original subview I used to create a UICollectionViewCell was a UIView. Even though I changed the class to a subclass of UICollectionViewCell, XCode still considered it a UIView, and hence the issues you see with contentView not catching touch events.

To fix this, I redid the nib by making sure to drag a UICollectionViewCell object, and moving all the subviews to that. Afterwards, touch events began to work on my cell's subviews.

Could indicator to see if your nib is configured as a UICollectionViewCell is look at the icon for your high level view.

enter image description here

If it doesn't look like this, then its probably going to interpret touch events wrong.


When you create a UICollectionViewCell via a nib the contents of the nib are not added to the cell's contentView -- it all gets added directly to the UICollectionViewCell. There doesn't appear to be a way to get Interface Builder to recognize the top-level view in the nib as a UICollectionViewCell, so all of the contents inside 'automatically' get added to the contentView.

As sunkehappy pointed out, anything that you want to receive touch events needs to go into the contentView. It's already been created for you, so the best you can do is to programmatically move your UIButton into the contentView at awakeFromNib-time.

-(void)awakeFromNib {    [self.contentView addSubview:self.myButton];}


UICollectionViewCell Class Reference

To configure the appearance of your cell, add the views needed to present the data item’s content as subviews to the view in the contentView property. Do not directly add subviews to the cell itself. The cell manages multiple layers of content, of which the content view is only one. In addition to the content view, the cell manages two background views that are display the cell in its selected and unselected states.

You can add your button in awakeFromNib like this:

- (void)awakeFromNib{    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];    [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];    [self.contentView addSubview:button];}- (void)buttonClicked:(id)sender{    NSLog(@"button clicked");}