SamG
SamG

Reputation: 173

Detect touch from an array of UIViews

I am working on a view controllers that has many UIview in a grid layout. Those views has some interaction (like buttons etc). But on touching that view, I want a new view controller to appear. I cannot find a way to check for a touch from these views. There's a method CGRectContainsPoint... but I have multiple UIViews.

Please help me out!

Upvotes: 0

Views: 193

Answers (2)

Simon Withington
Simon Withington

Reputation: 1485

Another way of tackling this problem would be to add gesture recognizers to your views to pick up taps:

UITapGestureRecognizer *tapGestureRecogniser = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(_method_:)];
    [_view_ addGestureRecognizer:tapGestureRecogniser];
    [tapGestureRecogniser release];

This would call method whenever the view is tapped. Hope this helps.

Upvotes: 0

Jeroen Coupé
Jeroen Coupé

Reputation: 1404

Have you tried?

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

   CGPoint point = [[touches anyObject] locationInView:self.view];
   if ( CGRectContainsPoint(subview1.frame, point))
   {
     //show viewcontroller1
   }
   if ( CGRectContainsPoint(subview2.frame, point))
   {
     //show viewcontroller2 
   }
} 

This way you should be able to determine which subview is touched.

The idea is that first you get your coordinates based on the self.view and then you can compare them with the subviews of the original view.

I think other possible solutoions could be:

1 Use keyValueObserving http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

or
2 NSNotificatonCenter messages http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

With both methods you can let your (sub)views signal your viewcontroller when your subview detect a touch and let the viewcontroller act accordingly.

Upvotes: 1

Related Questions