Wednesday, January 9, 2013

Handling Touch Events For UIButton in IOS



I recently used this code for handling touch events like touchesBegan,touchesMoved,touchesEnded  on UIButton in my project.

STEP 1:Create  UIButton Programmatically like this

1.UIButton *touchButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
2.    touchButton.frame=CGRectMake(303026050);
    [touchButton setTitle:@"TOUCH BUTTON" forState:UIControlStateNormal];
 3.   [touchButton addTarget:self action:@selector(touchBegan:withEvent:) forControlEventsUIControlEventTouchDown];
 4.   [touchButton addTarget:self action:@selector(touchMoving:withEvent:) forControlEventsUIControlEventTouchDragInside | UIControlEventTouchDragOutside];
  5.  [touchButton addTarget:self action:@selector(touchEnded:withEvent:) forControlEventsUIControlEventTouchUpInside | UIControlEventTouchUpOutside];
6. [self.view addSubview:touchButton];

In the above code  adding selectors for different control events is important.
if you want to recognize touchBegan Method on UIButton,you have to write the selector method like this 

[touchButton addTarget:self action:@selector(touchBegan:withEvent:) forControlEventsUIControlEventTouchDown];
if you want to recognize touchMoving Method on UIButton,you have to write the selector method like this 

[touchButton addTarget:self action:@selector(touchMoving:withEvent:) forControlEventsUIControlEventTouchDragInside | UIControlEventTouchDragOutside];
if you want to recognize touchEnded Method on UIButton,you have to write the selector method like this 

[touchButton addTarget:self action:@selector(touchEnded:withEvent:) forControlEventsUIControlEventTouchUpInside | UIControlEventTouchUpOutside];

STEP 2: Implement The Selector Methods For Touch Events Like this.
// this method calls whenever you touchDown on button
- (void)touchBegan:(UIButton *)control withEvent:event {
    NSLog(@"touchBegan called......");
    UITouch *touch = [[event allTouchesanyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@"In Touch Began: Touch x : %f y : %f", touchPoint.x, touchPoint.y);
    
}
// this method calls whenever you touchDragInside or touchDragOutside on button
- (void)touchMoving:(UIButton *)control withEvent:event {
    NSLog(@"touchMoving called......");
    UITouch *touch = [[event allTouchesanyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
     NSLog(@"In Touch Moving  :Touch x : %f y : %f", touchPoint.x, touchPoint.y);
   }

// this method calls whenever you touchUp inside or touchUp outside on button
- (void)touchEnded:(UIButton *)addOnButton withEvent:event {
    NSLog(@"touchEnded called......");
    UITouch *touch = [[event allTouchesanyObject];
    CGPoint touchPoint = [touch locationInView:self.view];
    NSLog(@" In Touch Ended : touchpoint.x and y is %f,%f",touchPoint.x,touchPoint.y);
}


Thank You.....

No comments:

Post a Comment