Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button not working in UITableViewCell subclass when it is a subview of a view inside the UITableViewCell

I have a button in a tableView Cell that I need to respond to touch events. Normally this would easily be solved by

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

inside of -tableView:cellForRowAtIndexPath:

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

for example:

    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 the button is a subview of a view that I create within the custom UITableViewCell then the cell is highlighted instead of the button being pressed so the target that I setup in -tableView:cellForRowAtIndexPath is never called. Not sure why.. any help?

Thanks,

Joel

PS. I realize that there probably isn't a practical reason to create a background view exactly like this since there already is one. This is just example code that I'm using to explain a problem I'm having.. :D

Thanks for Looking!

like image 972
Joel Bell Avatar asked Dec 28 '22 06:12

Joel Bell


2 Answers

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

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

I think that either userInteractionEnabled cascades to subviews or the superview will not pass the touch to its subviews in this case, so your button will not be receiving touches. Set your image view to have .userInteractionEnabled = YES and you should be fine.

like image 168
jrturton Avatar answered Dec 31 '22 14:12

jrturton


I had the same problem and tried EVERYTHING. The thing that finally did it was implementing the method

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

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

like image 45
Jeff Grimes Avatar answered Dec 31 '22 14:12

Jeff Grimes