Iphone 将TapGestureRecognitor添加到UITextView

Iphone 将TapGestureRecognitor添加到UITextView,iphone,uitextview,tap,Iphone,Uitextview,Tap,我想在UITextView中添加一个*UITapGestureRecognite*r,因为我想关闭文本视图所在的“弹出窗口”。所以我想,当点击T*extView*时,调用Popup类的方法“hide”。我尝试了以下方法,但由于某些原因,它不起作用: UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(show)]; [gr setNumberOfTaps

我想在UITextView中添加一个*UITapGestureRecognite*r,因为我想关闭文本视图所在的“弹出窗口”。所以我想,当点击T*extView*时,调用Popup类的方法“hide”。我尝试了以下方法,但由于某些原因,它不起作用:

UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(show)];
[gr setNumberOfTapsRequired:1];
[viewText addGestureRecognizer:gr];
我也不想为它创建子类,因为我需要调用“parent”-方法“hide”

也许你现在找到了解决这个问题的好办法。

提前感谢您。

您不应该使用UITapGestureRecognizer,而应该使用UITextFieldDelegate

您可以在此处阅读:

您基本上需要添加 UITextViewDelegate到您的.h文件,如下所示-

@interface MyViewController : UIViewController<UITextViewDelegate>
现在使用其中一种委派方法,可能是:

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

   // Do what you need to do...

}
编辑

我可以考虑另外两种方法:

  • 您可以将文本视图包装在UIView中,并将UIAPTestureRecognitor添加到视图中
  • 您可以使用:

     -(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
         }
     }
    

  • 祝你好运

    你是否尝试登录到show方法?或者您是否声明并编写了方法“show”?它应该是有效的,这就是我在文本视图中所做的


    另外,在添加textview:D后,别忘了释放你的手势实例(gr)

    我在工作时也遇到了重大问题,但我遇到了一个愚蠢的问题,用户交互在可视化编辑器中被关闭。希望这对某人有所帮助:)

    嗨,谢谢你的回答,但它不起作用。如果我点击TextView,则不会调用委托方法textViewShouldBeginEditing(我在其中添加了一个NSLog)。没有像textViewTouchesEndes之类的东西,对吧?嗯,不工作,也不需要(不应该是可编辑的)。难道没有办法让手势识别器工作吗?我现在让手势识别器工作了。属性“可编辑”需要设置为否,则识别器工作正常。
     -(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
         }
     }