7

In my view I want to add a target which should be fired when I click the view. I can do the same through IB or I have done it for buttons even in code. However I have no idea how to do it for UIView programatically.

Anyone has done that before.

Help me.

Newbee
  • 3,231
  • 7
  • 42
  • 74

2 Answers2

7

For clicking a UIView you have to use UIGestureRecognizer or UITouch. This would only help in prompting an action. The UIButton has a selector method whereas the UIView does not have any such method. Also , this is same for UIImageViews etc also.

IronManGill
  • 7,222
  • 2
  • 31
  • 52
  • Checkout these links then http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview and http://stackoverflow.com/questions/2041806/create-uiview-through-code-and-add-events-in-iphone , http://stackoverflow.com/questions/4130496/touch-event-on-uiview :) – IronManGill Oct 12 '12 at 10:17
5

You can acheive this using UIGestureRecognizer.

Step 1:

Add your UIView as a property in your viewcontroller

@property (strong, nonatomic) IBOutlet UIView *yourView;

Step 2:

Set UIGestureRecognizer for your UIView.

- (void)viewDidLoad {
    [super viewDidLoad];
    UIGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    [self.yourView addGestureRecognizer:gesture];
}

Step 3:

Handle the click on UIView.

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer {
    //to get the clicked location inside the view do this.
    CGPoint point = [gestureRecognizer locationInView:self.yourView];
}

Remember that A UIGestureRecognizer is to be be used with a single view.

Kousik
  • 21,485
  • 7
  • 36
  • 59