'Hold' UIButton Behaviour - `Touch Cancell

2020-08-01 06:35发布

问题:

I have a button on a subview view (for talk sake the subview is a red square) that when the user holds down on the button the red square animates translucent.

I have the button connected to this method:

-(IBAction)peekToggle:(id)sendr{        

    NSLog(@"TOGGLE");

    if(self.view.alpha ==1)self.view.alpha = 0.1;   
    else self.view.alpha = 1;       
}

Via the behaviours: touch up inside, touch up outside and touch down. so when i hold the button down the red box goes transluscent and when i release my finger it returns to opaque. This initially works fine, however if i hold the button down for more than 1 second, the button does not register the touch up (release of the finger).

NB:I do have a longPressGestureRecogniser on the parent view (parent of subview not parent of Button) but its not being fired (expected).

Im pretty sure my long press on the button being registered as a touch cancel and then invalidating the touch up event.

How can I prevent/work around this?

Can I Stop the touch Cancel Firing? (this event seems to fire even if i havant registered the control state) or in the touch Cancel event, tell the button to keep/start registering events?

回答1:

SOLUTION:

Removed the IBActions completely and added UILongPressGestureRecognizer to the button with a very short min duration.

    UILongPressGestureRecognizer * recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];    
        recognizer.minimumPressDuration = 0.1;  
        [self.peekButton.view addGestureRecognizer:recognizer];
        [recognizer release];

Then in the selector for the gr, read the gr's state:

    - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer{ 

        //1 = start
        if(gestureRecognizer.state==1 || gestureRecognizer.state==3)[self peekToggle];
        //3=end
}


回答2:

If you think that's your problem, you can try overriding - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event and see if you get any activity there.



回答3:

You can use the UIGestureRecognizerDelegate interface to fine-tune when your gesture recognizer gets fired.