Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add TapGestureRecognizer to UITextView

I want to add an *UITapGestureRecognize*r to my UITextView, because I want to close a "Popup" where the TextView is in. So I want, that the method "hide" of the Popup class is called, when the T*extView* is tapped. I tried it like the following, but it isn't working for some reason:

UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(show)];
[gr setNumberOfTapsRequired:1];
[viewText addGestureRecognizer:gr];

I also don't want to create a Subclass for it, because I then would need to call the "parent"-method "hide".

Maybe you now a good solution for that problem.
Thank you in advance.

like image 876
Kevin Glier Avatar asked Dec 19 '25 21:12

Kevin Glier


1 Answers

You shouldnt use UITapGestureRecognizer but use the UITextFieldDelegate.

You can read about it here:

http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html%23//apple_ref/doc/uid/TP40006897

You basicly need to add the UITextViewDelegate to your .h file like that -

@interface MyViewController : UIViewController<UITextViewDelegate>

Then assign your controller as the delegate:

viewText.delegate =self;

Now use one of the delegation methods, maybe:

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{

   // Do what you need to do...

}

Edit

Well I can think on 2 additional approaches:

  1. You can wrap your textView inside a UIView and add the UITapGestureRecognizer to the view.
  2. You can use :

     -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
         UITouch *touch = [touches anyObject];
         CGPoint location = [touch locationInView:textView];
    
         //Checks if the tap was inside the textview bounds
         if (CGRectContainsPoint(textView.bounds, location)){
             //do something
         }
     }
    

Good luck

like image 114
shannoga Avatar answered Dec 22 '25 16:12

shannoga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!