检测UIGestureRecognizer点击并释放以显示和删除UIView

时间:2016-04-19 10:41:32

标签: ios xcode swift

当用户点按并按住UIView中的单元格时,我想在屏幕上显示UICollectionView,并在用户移开手指时将其删除。 (像Snapchat这样的东西)。

这是我的一些代码 - 出了什么问题?当我按下时,UIView显示出来,但当我松开手指时它不会消失..

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 个答案:

答案 0 :(得分:0)

  1.   

    图像显示前需要3-5秒

    这可能是因为您使用的是UILongPressGestureRecognizer,而不是UITapGestureRecognizer

  2. 在您的代码中,您没有处理state.Cancelled的情况。这可能会阻止您在用户抬起手指时移除视图。