UILongPressGestureRecognizer not working on UITextField

与世无争的帅哥 提交于 2020-01-06 08:19:08

问题


I have a LongPress gesture recognizer initialized in the viewDidLoad method of my viewcontroller as below:

longPressGesture_= [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(displayTimeFlagCallout)];

I have a tableview in my viewcontroller. The tableview has custom cells. Each cell has 2 textfields. I want to bring up a custom popover when a user long presses on the text fields (startTime and endTime). I do not want the magnifying glass and the Copy/Paste popover to show up on long press of textfield as the standard behavior and hence before adding my gesture recognizer, I am disabling the in-built long press gesture recognizer of the text fields. I have added the following code to my cellforRowAtIndexPath method:

MyCustomCell_iPhone *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

if (cell == nil)
  {
    cell = [[MyCustomCell_iPhone alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];


      for (UIGestureRecognizer *recognizer in cell.startTime.gestureRecognizers) {
          if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
              recognizer.enabled = NO;
          }
      }
      for (UIGestureRecognizer *recognizer in cell.endTime.gestureRecognizers) {
          if ([recognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
              recognizer.enabled = NO;
          }
      }

      [cell.startTime addGestureRecognizer:longPressGesture_];
      [cell.endTime addGestureRecognizer:longPressGesture_];


  }

However, this is not working. Nothing happens on long press now. Any ideas what could be the issue?

Thanks Hetal


回答1:


Three thoughts:

  1. You cannot use the same long press gesture recognizers for two controls. You have to create a separate gesture recognizer for each control.

  2. It would appear that the gesture recognizers get reset when you start editing in text field (assuming you allow editing in the text field). I assume you allow editing of the text field, and, if so, I believe that you have to set a delegate that will disable the long gesture recognizer that is not your own. (You can do that, for your long press gesture recognizer, subclass it as, say CustomLongPressGestureRecognizer, use that for your text field's gesture recognizers and then you can disable any UILongPressGestureRecognizer objects that are not your own CustomLongPressGestureRecognizer.)

  3. I infer from your code that you're not using storyboards and prototype cells, because in that scenario, cell is never nil and your if statement would never end up invoking your code. But if you're using NIBs or not using prototype cells, then you should be fine on this point.



来源:https://stackoverflow.com/questions/13653415/uilongpressgesturerecognizer-not-working-on-uitextfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!