开发者

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 addGestureReco开发者_JS百科gnizer: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.


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


Did you try to NSLog on show method? or did you even declare and write method "show" ? It should work and that's how I did on my text view.

P.S don't forget to release your gesture instance (gr) after you add on textview :D


I had major problems getting this working also but I had one stupid problem, user interaction was turned off in the visual editor. Hope this helps someone :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜