Search code examples
iphoneobjective-cuibuttonuitouch

UIButton crashes on uitouch event


I have a UIButton which sends the draginside event to:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {

It does this through the following code in viewDidLoad:

[colourButton1 addTarget:self action:@selector(touchesBegan:withEvent:) forControlEvents:UIControlEventTouchDown];

Within the method it sends it to, there is the following line:

UITouch *myTouch = [touches anyObject];

And for some reason, when dragging inside the UIButton this crashes the app. Any ideas why?

EDIT: The solution..

-(IBAction)buttonDragged:(id)button withEvent:(UIEvent*)event {
    NSSet *touches = [event touchesForView:colourButton1];
    [self touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event];
}

Solution

  • When you're adding target to control you can pass 3 types of selectors for action -

    - (void)action
    - (void)action:(id)sender
    - (void)action:(id)sender withEvent:(UIEvent*)event
    

    Names don't matter, it's number of parameter which is important. If control sends it's target a message with 2 params then first parameter will be control itself (instance of UIButton in your case), second one - instance of UIEvent. But you expects instance of NSSet as first parameter and send it a message anyObject which UIButton doesn't understand. This is the cause of crash.

    Why are you trying to send event from UI control to touch handling method touchesMoved:withEvent: in the first place? It will probably do something different from what you meant.

    UPDATE:

    - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent *)event {
        UITouch *t = [touches anyObject];
        CGPoint touchLocation = [t locationInView:self.view];
        NSLog(@"%@", NSStringFromCGPoint(touchLocation));
    }
    
    
    - (IBAction)buttongDragged:(id)button withEvent:(UIEvent*)event {
        NSSet *touches = [event touchesForView:button];
        [self touchesMoved:touches withEvent:event];
    }
    

    Notice that since touchesMoved:withEvent: is a UIResponder's method and controller's view is UIResponder this method will be also called on touch events for this view.