0

I am using the following code to call a function when somebody clicks on a button within a UITableViewCell. Unfortunately the code still gets called even when the touch is released outside of the button area. (e.g touch the button, slide finger off button and button is still actioned).

Can somebody please tell me why this happens, or what the correct way of doing this is? I thought that perhaps my problem was with the "addTarget" clause - i.e perhaps the TouchUpInside is referring to my UITableView rather than the button itself??

[cellPeriod.myButton1 addTarget:self action:@selector(buttonClickedStopWatch:) forControlEvents:UIControlEventTouchUpInside];
SparkyNZ
  • 6,266
  • 7
  • 39
  • 80

1 Answers1

2

The problem has no relationship with the UITableView.

I think maybe Apple is deliberately doing so , because of our fingers are not the mouse. You can check the app producted by Apple, it also has the problem. You can see the backItemButton of the navigationBar.

If you want to solve it , you can do with the UIControl's method :

 - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event; 

To check this point whether inside the rect of the button. And you can add a BOOL value to decide whether to go on to do the selector

added:

#import "MyButton.h"

@implementation MyButton

- (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    CGPoint location = [touch locationInView:self];
    CGRect btnRect = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    if (CGRectContainsPoint(btnRect, location)) {
        self.tag=-1;
        return;
    }
    self.tag=-2;
}
@end
cloosen
  • 993
  • 7
  • 17
  • Thanks for the response. I don't follow entirely what you are suggesting. I hear what you are saying about using the endTrackingWithTouch method instead.. but how are you suggesting that the selector is conditionally called? Could you provide an example please? Thanks – SparkyNZ Jul 23 '12 at 07:59
  • @SparkyNZ 1)you can use MyButton:UIButton or UIControl, and use - (void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event;you can look at the code what i added,it can use although it is very ugly. 2)Another method is use - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; in tableView or tableViewController.view.you can try – cloosen Jul 23 '12 at 11:55
  • Great thanks - I'll give this a try tonight! Its helpful seeing code like this - also helps me navigate the Apple documentation better too, – SparkyNZ Jul 25 '12 at 19:51