问题
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:
You cannot use the same long press gesture recognizers for two controls. You have to create a separate gesture recognizer for each control.
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 anyUILongPressGestureRecognizer
objects that are not your ownCustomLongPressGestureRecognizer
.)I infer from your code that you're not using storyboards and prototype cells, because in that scenario,
cell
is nevernil
and yourif
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