简体   繁体   中英

Detect UIGestureRecognizer tap and release to show and remove UIView

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM