Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 362
Newbee Avatar asked Oct 12 '12 10:10

Newbee


2 Answers

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.

like image 159
IronManGill Avatar answered Nov 13 '22 11:11

IronManGill


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.

like image 5
Nullify Avatar answered Nov 13 '22 11:11

Nullify