Detect UIGestureRecognizer tap and release to show

2019-09-11 04:44发布

问题:

I want to show up a UIView over the screen when the user tap and hold down a cell in my UICollectionView, and remove it when the user removes the finger. (Something like snapchat had).

This is some of my code - what is wrong? When I press, the UIView shows up, but it doesn't go away when I release my finger..

func handleLongPress(gestureRecognizer : UILongPressGestureRecognizer){
    // screen width and height:
    let width = UIScreen.mainScreen().bounds.size.width
    let height = UIScreen.mainScreen().bounds.size.height

    var myView = UIView(frame: CGRectMake(0, 0, width, height))
    myView.backgroundColor = UIColor.greenColor()
    myView.userInteractionEnabled = true


    if (gestureRecognizer.state == UIGestureRecognizerState.Began){
        let p = gestureRecognizer.locationInView(self.collectionView)

        if let indexPath : NSIndexPath = (self.collectionView?.indexPathForItemAtPoint(p))!{
            print("Tap began")
            self.view.addSubview(myView)
        }
    }

    if (gestureRecognizer.state != UIGestureRecognizerState.Ended){
        return
    }

    if (gestureRecognizer.state != UIGestureRecognizerState.Cancelled){
        myView.removeFromSuperview()
        print("Cancelled")
    }

    let p = gestureRecognizer.locationInView(self.collectionView)

    if let indexPath : NSIndexPath = (self.collectionView?.indexPathForItemAtPoint(p))!{
        //do whatever you need to do
        print("Tap released")
        myView.removeFromSuperview()
    }
}

回答1:

  1. it takes 3-5 seconds before the image shows up

    That's probably because you are using UILongPressGestureRecognizer, not a UITapGestureRecognizer.

  2. In your code you didn't handle case where state is .Cancelled. That could prevent your view from removing when user lifts finger.



标签: ios xcode swift