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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With