6

How to get touch on a particular view.

I am using

CGPoint Location = [[touches anyObject] locationInView:self.view ];

but want to trigger the action only if an particular subView is clicked.
How to do this.

Hiren
  • 12,720
  • 7
  • 52
  • 72
Kumar sonu
  • 535
  • 11
  • 24

6 Answers6

8

I got the answer myself...but thanks other which helped me on this

here it is

UITouch *touch ;
touch = [[event allTouches] anyObject];


    if ([touch view] == necessarySubView)
{
//Do what ever you want
}
Kumar sonu
  • 535
  • 11
  • 24
8

Try this

//here enable the touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    if (CGRectContainsPoint(yoursubview_Name.frame, touchLocation)) {
        //Your logic
        NSLog(@" touched");
    }
}
Bishal Ghimire
  • 2,580
  • 22
  • 37
Sat
  • 1,616
  • 3
  • 22
  • 40
1

Heres a swift3 version without multitouch:

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first, self.bounds.contains(touch.location(in: self)) {
        // Your code
    }
}
kiecodes
  • 1,642
  • 14
  • 28
1

You should create a subclass (or create a category) of UIView and override the

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

where redirect the message to the appropriate delegate.

Max
  • 16,679
  • 4
  • 44
  • 57
1
// here Tiles is a separate class inherited from UIView Class
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([[touch view] isKindOfClass:[Tiles class]]) {
        NSLog(@"[touch view].tag = %d", [touch view].tag);
    }
}

like this you can find view or subview is touched

User-1070892
  • 929
  • 10
  • 16
0

Did u try

CGPoint Location = [[touches anyObject] locationInView:necessarySubView ];
visakh7
  • 26,380
  • 8
  • 55
  • 69