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(30, 30, 260, 50);
[touchButton setTitle:@"TOUCH BUTTON" forState:UIControlStateNormal];
3. [touchButton addTarget:self action:@selector(touchBegan:withEvent:) forControlEvents: UIControlEventTouchDown];
4. [touchButton addTarget:self action:@selector(touchMoving:withEvent:) forControlEvents: UIControlEventTouchDragInside | UIControlEventTouchDragOutside];
5. [touchButton addTarget:self action:@selector(touchEnded:withEvent:) forControlEvents: UIControlEventTouchUpInside | 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:) forControlEvents: UIControlEventTouchDown];
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:) forControlEvents: UIControlEventTouchDragInside | 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:) forControlEvents: UIControlEventTouchUpInside | 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 allTouches] anyObject];
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 allTouches] anyObject];
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 allTouches] anyObject];
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