Tap Gesture with UIGestureRecognizerState not work

2019-08-05 08:47发布

问题:

I have a view with a tap gesture applied to it. I want to have the view "shrink" when someone's finger is on the view and have the view go back to normal when the finger is lifted. I'm trying to achieve this with a UIGestureRecognizerState but it's not working. The view shrinks only after I remove my finger and does not go back. Here's my code:

@IBAction func shareButton(sender: AnyObject) {

    if sender.state == UIGestureRecognizerState.Changed {  
        UIView.animateWithDuration(0.1, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: nil, animations: {
            self.shareButton.transform = CGAffineTransformMakeScale(0.9, 0.9)
        }, completion: nil)
    } else if sender.state == UIGestureRecognizerState.Ended {
        UIView.animateWithDuration(0.1, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: nil, animations: {
            self.shareButton.transform = CGAffineTransformMakeScale(0.7, 0.7)
        }, completion: nil)
    }
}

回答1:

var delaysTouchesEnded: Bool // default is YES.

causes touchesEnded events to be delivered to the target view only after this gesture has failed recognition. this ensures that a touch that is part of the gesture can be cancelled if the gesture is recognised

So it will call the action next time as operation will be performed only after tap action will be performed. As action method will perform when touch has ended.

But you can use touchesBegin and touchesEnded method. If you are using tap gesture for that it won’t work as it action methods will be called when your touch will be released. You can also use long press gesture for shrinking view.

override func

touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        UIView.animateWithDuration(1, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: nil,
            animations: {
                self.vwBlue.transform = CGAffineTransformMakeScale(0.5, 0.5)
            }, completion: nil)
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        UIView.animateWithDuration(1, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: nil,
            animations: {
                self.vwBlue.transform = CGAffineTransformMakeScale(1, 1)
            }, completion: nil)
    }


回答2:

I think you could try to add two targets to your view. Shrink animation for a UIControlEventTouchDown and the other for UIControlEventTouchUpInside or one of the other events depending on what should happen? Ref iOS docs