Newbee
Newbee

Reputation: 3301

Add target for UIView Programmatically

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.

Upvotes: 7

Views: 9749

Answers (2)

Kousik
Kousik

Reputation: 22465

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.

Upvotes: 5

IronManGill
IronManGill

Reputation: 7226

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.

Upvotes: 7

Related Questions