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

标签 ios xcode swift

我想在用户点击并按住 UICollectionView 中的单元格时在屏幕上显示 UIView,并在用户移开手指时将其删除。 (类似于 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. it takes 3-5 seconds before the image shows up

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

  2. 在您的代码中,您没有处理 state.Cancelled 的情况。这可以防止当用户抬起手指时您的 View 被移除。

关于ios - 检测 UIGestureRecognizer 点击并释放以显示和删除 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36715993/

相关文章:

c# - UITextField TextColor 属性绑定(bind)问题(MVVMCross)

ios - 为什么我的 Swift Playground 中什么都没有显示?

ios - 使用 AFNetworking 获取请求并保存响应

ios - Swift 中的 NSDate 排序

arrays - 如何根据父数组的键引用子数组?

ios - 处理自动布局

xcode - 有没有办法在 Swift 中更改 NSTextView 容器的字符串值?

iphone - 使用 Xcode 实现向后兼容的目标 iOS 级别

ios - Smart App 横幅可以启动从 Xcode 安装的应用程序吗?

swift - 如何解决 requestAccess 中的无限循环(到 :completion:) on EKEventStore?