Kumar sonu
Kumar sonu

Reputation: 535

how identify touch in a particular view

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.

Upvotes: 6

Views: 8993

Answers (6)

Sat
Sat

Reputation: 1626

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");
    }
}

Upvotes: 8

kiecodes
kiecodes

Reputation: 1659

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
    }
}

Upvotes: 1

User-1070892
User-1070892

Reputation: 929

// 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

Upvotes: 1

Kumar sonu
Kumar sonu

Reputation: 535

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
}

Upvotes: 8

visakh7
visakh7

Reputation: 26390

Did u try

CGPoint Location = [[touches anyObject] locationInView:necessarySubView ];

Upvotes: 0

Max
Max

Reputation: 16709

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.

Upvotes: 1

Related Questions