I am using a subclass of UIView in my app. When the user touches on view I need to get the coordinates of the point; for this I am using:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{
currentPoint=[[touches anyObject]locationInView:self];
}
It has some delay. Can any one give me the solution to get the points immediately? Thank you all.
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code.
self.frame=frame;
rect=[[NSMutableArray alloc] initWithCapacity:1];
currentPointsList=[[NSMutableArray alloc]initWithCapacity:1];
}
return self;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
firstTouchedPoint = [touch locationInView:self];
NSLog(#"the firstTouched point is %");
for (int i=0; i<[rect count]; i++) {
if(CGRectContainsPoint([[rect objectAtIndex:i]CGRectValue], firstTouchedPoint)){
CGRect firstLineRect = CGRectMake(firstTouchedPoint.x,
[[rect objectAtIndex:i]CGRectValue].origin.y,
[[rect objectAtIndex:i]CGRectValue].size.width-firstTouchedPoint.x+[[rect objectAtIndex:i]CGRectValue].origin.x,
[[rect objectAtIndex:i]CGRectValue].size.height);
UIImageView *firstLine=[[UIImageView alloc]initWithFrame:firstLineRect];
firstLine.backgroundColor=[[UIColor blueColor]colorWithAlphaComponent:0.3f];
[self addSubview:firstLine];
break;
}
}
If you are using a UIScrollView there is a delay touches property (delaysContentTouches). You may want to make sure that is NO.
Related
I am currently working on a 3D OpenGLES-based iPhone Game project and I want to have a view that detect touches so I can then rotate my camera according to the touch gestures.
So here I created a TouchPad class that derives from UIView to record the touch gestures.
Once done I have figured out that only half of the screen is effective. The whole left side.
Whenever i touch the right part of the screen it does not call the -[touchesBegan] method
Here is my class definition
#interface TouchPad : UIView
{
CGPoint fingerMove, originalPosition;
}
#property (nonatomic, assign) CGPoint fingerMove;
#end
And here is my class implementation
#import "TouchPad.h"
#implementation TouchPad
#synthesize fingerMove;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
fingerMove = CGPointMake(0, 0);
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
std::cout << "called";
UITouch *touch = [touches anyObject];
originalPosition = [touch locationInView:self];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPosition = [touch locationInView:self];
fingerMove = CGPointMake(currentPosition.x - originalPosition.x,
currentPosition.y - originalPosition.y);
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
{
UITouch *touch = [touches anyObject];
originalPosition = [touch locationInView:self];
fingerMove = CGPointMake(0, 0);
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
fingerMove = CGPointMake(0, 0);
}
#end
And here is how i use it inside my ViewController
- (void)prepareGame
{
game = [[MainGame alloc] init];
[self.view addSubview:game.IrrView];
[game.IrrView release];
rotationPad = [[TouchPad alloc] initWithFrame:CGRectMake(0.0, 0.0,
[[UIScreen mainScreen] bounds].size.width,
[[UIScreen mainScreen] bounds].size.height)];
[self.view addSubview:rotationPad];
[rotationPad release];
}
- (void)runGame
{
[game updateMapPattern];
[game updateCamera :rotationPad.fingerMove];
[game draw];
}
I really want to know how to make the touchPad work in the whole screen and not only the left part of the screen. Maybe there is a conflict with my game view
I have a view with subViews, these subViews are a subClass of UIView, in the example the subClass is called ESDcelda
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
UIImage *img = [UIImage imageNamed:#"lgrey091.gif"];
[self setBackgroundColor:[UIColor colorWithPatternImage:img]];
ESDcelda *cel1 = [[ESDcelda alloc] initWithTipo:1];
[cel1 setFrame:CGRectMake(100, 100, cel1.frame.size.width, cel1.frame.size.height)];
[self addSubview:cel1];
cel1 = [[ESDcelda alloc] initWithTipo:2];
[cel1 setFrame:CGRectMake(300, 100, cel1.frame.size.width, cel1.frame.size.height)];
[self addSubview:cel1];
}
return self;
}
now I'm triyng to know what kind of UIView I am pointing with the touchEvents with the following methods but in the log the pointer "vista" only recognizes the self class or the UIView class, there is any way to recognize the subClass "celdaSel" ?
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
}
-(void)perfTouch:(UITouch *)touch
{
CGPoint punto = [touch locationInView:self];
UIView *vista = (ESDcelda *)[self hitTest:punto withEvent:nil];
if (![vista isKindOfClass:[self class]])
{
celdaSel = (ESDcelda *)vista;
[celdaSel seleccion:YES];
}
else
{
if (celdaSel != nil)
{
[celdaSel seleccion:NO];
}
}
}
Solved, there are the steps
In the main view only left the code that interpects the touch and where is it.
v
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[touches allObjects] objectAtIndex:0];
[self perfTouch:touch];
if (self.celdaSel != nil)
{
NSLog(#"%d",self.celdaSel.elemento);
}
}
-(void)perfTouch:(UITouch *)touch
{
CGPoint punto = [touch locationInView:self];
[self hitTest:punto withEvent:nil];
}
In the UIView subClass called ESDCelda I override pointInside:withEvent method to know if the current single touch is on the view, "inter" is the variable that lets me know if the touch is on the view, "seleccionada" indicates if the view is highlighted, "conten" is a pointer to the superview, and "seleccion:" is the method that highlights the view it self.
v
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
BOOL inter = [super pointInside:point withEvent:event];
if (inter)
{
//NSLog(#"%i, %#", inter, self);
if (!self.selecionada)
{
[self seleccion:YES];
if (self.conten.celdaSel != nil)
[self.conten.celdaSel seleccion:NO];
[self.conten setCeldaSel:self];
}
}
else
{
if (self.selecionada)
{
[self seleccion:NO];
[self.conten setCeldaSel:nil];
}
}
return inter;
}
My view has a UIPanGestureRecognizer added to it.
The problem is that by the time the touch is recognized as a pan gesture, it has to be moved a few points, and I can't extract the original touch location at the UIGestureRecognizerStateBegan state.
In this state the translationInView: is (0,0), and any subsequent moves are calculated from this point, and not from the original.
Is there a way to extract the original location from the gesture recognizer itself, or do I need to override the touchesBegan: method?
You should be able to set the delegate for the gesture recogniser and implement
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
to get the initial touch.
You can solve this problem by implementing a custom PanGestureRecognizer which saves the original touch point and makes it available to the caller.
I went this route as I also wanted to control the distance moved to trigger a pan gesture.
This might be overkill for your situation, but works perfectly and is less difficult than it sounds.
To get the touchpoint coordinates, you just call:
[sender touchPointInView:yourView]
instead of:
[sender locationInView:yourView]
Here's the code for PanGestureRecognizer.m:
#import "PanGestureRecognizer.h"
#import <UIKit/UIGestureRecognizerSubclass.h>
#implementation PanGestureRecognizer
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
UITouch *touch = [touches anyObject];
// touchPoint is defined as: #property (assign,nonatomic) CGPoint touchPoint;
self.touchPoint = [touch locationInView:nil];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
UITouch *touch = [touches anyObject];
CGPoint p = [touch locationInView:nil];
// customize the pan distance threshold
CGFloat dx = fabs(p.x-self.touchPoint.x);
CGFloat dy = fabs(p.y-self.touchPoint.y);
if ( dx > 2 || dy > 2) {
if (self.state == UIGestureRecognizerStatePossible) {
[self setState:UIGestureRecognizerStateBegan];
}
else {
[self setState:UIGestureRecognizerStateChanged];
}
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
if (self.state == UIGestureRecognizerStateChanged) {
[self setState:UIGestureRecognizerStateEnded];
}
else {
[self setState:UIGestureRecognizerStateCancelled];
}
}
- (void) reset
{
}
// this returns the original touch point
- (CGPoint) touchPointInView:(UIView *)view
{
CGPoint p = [view convertPoint:self.touchPoint fromView:nil];
return p;
}
#end
If you use locationInView: rather than translationInView: you will get absolute coordinates instead of relative coordinates. However you do have to start the pan to get input... To work around this your view can be a UIButton and you can trigger a - (IBAction)buttonWasTouched:(UIButton *)button forEvent:(UIEvent *)event connected to "touch down" like so:
-(IBAction)shakeIntensityPanGesturebuttonWasTouched:(UIButton *)button forEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view]; //touch location local cordinates
}
You can use the UIGestureRecognizerState
- (void) onPanGesture:(UIPanGestureRecognizer *)sender {
if(sender.state == UIGestureRecognizerStateBegan) {
origin = [sender locationInView];
} else {
current = [sender locationInView];
// Initial touch stored in origin
}
}
Swift (ish):
var state = recognizer.state
if state == UIGestureRecognizerState.Began {
println(recognizer.locationInView(viewForGesture))
//this will be the point of first touch
}
How can I detect touch points in my UIScrollView? The touches delegate methods are not working.
Set up a tap gesture recognizer:
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(singleTapGestureCaptured:)];
[scrollView addGestureRecognizer:singleTap];
and you will get the touches in:
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
CGPoint touchPoint=[gesture locationInView:scrollView];
}
You can make your own UIScrollview subclass and then you can implement the following:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
NSLog(#"DEBUG: Touches began" );
UITouch *touch = [[event allTouches] anyObject];
[super touchesBegan:touches withEvent:event];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"DEBUG: Touches cancelled");
// Will be called if something happens - like the phone rings
UITouch *touch = [[event allTouches] anyObject];
[super touchesCancelled:touches withEvent:event];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"DEBUG: Touches moved" );
UITouch *touch = [[event allTouches] anyObject];
[super touchesMoved:touches withEvent:event];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"DEBUG: Touches ending" );
//Get all the touches.
NSSet *allTouches = [event allTouches];
//Number of touches on the screen
switch ([allTouches count])
{
case 1:
{
//Get the first touch.
UITouch *touch = [[allTouches allObjects] objectAtIndex:0];
switch([touch tapCount])
{
case 1://Single tap
break;
case 2://Double tap.
break;
}
}
break;
}
[super touchesEnded:touches withEvent:event];
}
If we're talking about the points inside the scrollview then you can hook with the delegate method:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
and inside the method, read the property:
#property(nonatomic) CGPoint contentOffset
from the scrollView to get the coordination.
This works also on touch down event.
In the currently as correct marked answer you can get a touch point only at a "Tap" event. This event seems only to fire on "finger up" not on down.
From the comment of yuf in the same answer you can get the touch point from the underlying view also within the UIScrollView.
- (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldReceiveTouch:(UITouch*)touch
{
CGPoint touchPoint = [touch locationInView:self.view];
return TRUE; // since we're only interested in the touchPoint
}
According to Apple's documentation the gestureRecognizer does:
Ask the delegate if a gesture recognizer should receive an object representing a touch.
which means to me that I can decide if a gestureRecognizer should recieve a touch or not.
I've got a set of Images and would like to know which I have touched. How could I implement that...?
To be more precise:
A "Home-Class" will instantiate a couple of Image-Classes:
Image *myImageView = [[Image alloc] initWithImage:myImage];
The image-class looks something like this:
- (id) initWithImage: (UIImage *) anImage
{
if ((self = [super initWithImage:anImage]))
{
self.userInteractionEnabled = YES;
}
return self;
}
later on, I use these touches-event-methods also in the Image-class:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{}
My problem at the moment: the touchesBegan/Ended methods will be fired no matter where I touched the screen, but I would like to find out which of the Images has been touched.....
Whenever you get the touch, you check if that touch happen in between your image area. Here is the example code, lets suppose you have UIImage object called img.
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:self.view];
if (location.x >= img.x && location.x <= img.x && location.y >= img.y && location.y <= img.y) {
// your code here...
}
}
Inside your *.h (interface) file:
#interface MyViewController : UIViewController{
IBOutlet UIImageView *imageViewOne;
IBOutlet UIImageView *imageViewTwo;
UIImageView * alphaImage;
}
-(BOOL)isTouch:(UITouch *)touch WithinBoundsOf:(UIImageView *)imageView;
Place UIImageView components on your *.xib and bind them with 'imageViewOne' and 'imageViewTwo' using the "File's owner".
Go to the *.m (implementation) file and:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([self isTouch:touch WithinBoundsOf:imageViewOne])
{
NSLog(#"Fires first action...");
}
else if([self isTouch:touch WithinBoundsOf:imageViewTwo]){
NSLog(#"Fires second action...");
}
}
//(Optional 01) This is used to reset the transparency of the touched UIImageView
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
[alphaImage setAlpha:1.0];
}
-(BOOL)isTouch:(UITouch *)touch WithinBoundsOf:(UIImageView *)imageView{
CGRect _frameRectangle=[imageView frame];
CGFloat _imageTop=_frameRectangle.origin.y;
CGFloat _imageLeft=_frameRectangle.origin.x;
CGFloat _imageRight=_frameRectangle.size.width+_imageLeft;
CGFloat _imageBottom=_frameRectangle.size.height+_imageTop;
CGPoint _touchPoint = [touch locationInView:self.view];
/*NSLog(#"image top %f",_imageTop);
NSLog(#"image bottom %f",_imageBottom);
NSLog(#"image left %f",_imageLeft);
NSLog(#"image right %f",_imageRight);
NSLog(#"touch happens at %f-%f",_touchPoint.x,_touchPoint.y);*/
if(_touchPoint.x>=_imageLeft &&
_touchPoint.x<=_imageRight &&
_touchPoint.y>=_imageTop &&
_touchPoint.y<=_imageBottom){
[imageView setAlpha:0.5];//optional 01 -adds a transparency changing effect
alphaImage=imageView;//optional 01 -marks the UIImageView which deals with the transparency changing effect for the moment.
return YES;
}else{
return NO;
}
}
That's how I handled that. I got the idea having read the post of "itsaboutcode".