Search code examples
uibuttonuicontrolevents

UIButton Correct TouchUp detection


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];

Solution

  • 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