Eyal
Eyal

Reputation: 10828

Objective c - Button inside a tableview prevent table from scrolling

I got a tableView with two buttons in each row, user of course can scroll to see more rows, or can tap on a button to see the item details.

The problem:

When user swipe his finger up or down, the table scroll well, but when the user hold down his finger on a button for more then one second and then move his finger up or down, the table doesn't scroll. I don't want this behavior, I want that the tableview will get the first priority, so it will scroll and the button event won't fire.

How can I prevent this from happening? the code to set the target for the button is this:

[cell.buttonLeft addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; 

Upvotes: 3

Views: 867

Answers (2)

Paradox
Paradox

Reputation: 94

If you're using IB, you can add a button to the cell (in IB), modify its tag, and then add the target and action to the button with that tag.

UIButton *button = (UIButton *)[cell.contentView viewWithTag:1002];
    [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];

Upvotes: -1

Shamsudheen TK
Shamsudheen TK

Reputation: 31311

Use UITapGestureRecognizer instead of using addTarget:

Example:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(aMethod:)];
[button addGestureRecognizer:tapGestureRecognizer];
[button setTitle:@"Show View" forState:UIControlStateNormal];

button.frame = CGRectMake(0, 0, 160.0, 40.0);
[cell.contentView addSubview:button];


-(void)aMethod:(UITapGestureRecognizer * )sender{

    if(sender.state == UIGestureRecognizerStateEnded)
    {
         NSLog(@"triggered");
    }
}

Upvotes: 4

Related Questions