A button that does not work in a subclass of UITableViewCell when it is a subview of a view inside a UITableViewCell

I have a button in CellView Cell, I need to respond to touch events. This is usually easy to solve with

[cell.playButton addTarget:self action:@selector(playButtonPressed:) forControlEvents:UIControlEventTouchUpInside]; 

inside -tableView: cellForRowAtIndexPath:

The problem I am facing is that my button is inside a custom subclass of UITableViewCell and is also a subview of the view that I create inside this class.

eg:

  UIView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; self.theView = view; [self addSubview:view]; [view release]; UIButton *playButton = [UIButton buttonWithType:UIButtonTypeCustom]; playButton.frame = CGRectMake(5, 5, 100, 30); [playButton setImage:[UIImage imageNamed:@"button_playvid.png"] forState:UIControlStateNormal]; [playButton setImage:[UIImage imageNamed:@"button_playvid_active.png"] forState:UIControlStateHighlighted]; self.playButton = playButton; [self.theView addSubview:playButton]; 

When a button is a subview of a view that I create in a custom UITableViewCell, the cell is highlighted instead of clicking the button, so the target that I set up in -tableView: cellForRowAtIndexPath is never called. Not sure why .. any help?

Thanks,

Joel

PS. I understand that there is probably no practical reason for creating a background view in the same way as it already is. This is just an example of the code that I use to explain my problem ..: D

Thanks for watching!

+4
source share
3 answers

The UIView you add is actually a UIImageView. From the docs:

New image viewers are configured to ignore user default events. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property in YES after initializing the object.

I think that either userInteractionEnabled cascades into subviews, or the supervisor will not transmit a touch to its subzones in this case, so your button will not receive touches. Set .userInteractionEnabled = YES for your image .userInteractionEnabled = YES and everything will be fine.

+9
source

I had the same problem and tried ALL. The fact is that in the end the method was implemented

 (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 

Just return any height of your custom cell (look in the NIB file)

+1
source

Instead of a button, you can try the same with the image. You can determine which method to call when you click on the image.

0
source

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


All Articles