LongPressEnded后,Swift从SuperViews删除视图

时间:2018-02-25 13:44:18

标签: swift

我试图在longPress结束后从superView中删除imageView和backgroundView。我已经咨询了应该有效的解决方案herehere。我想要实现的是当我在我的collectionViewCell中使用imageView时,它会缩小图像,当我释放触摸时,imageView会缩放回单元格的位置,然后removeFromSuperview()

我当前的代码没有动画,也没有从.ended块中的视图中删除blackBackgroundView和zoomingImageView。两种观点都留在了视野中。

@objc func longPressOnImage(gestureRecognizer: UILongPressGestureRecognizer) {
        let gestureState = gestureRecognizer.state
        let cell = gestureRecognizer.view?.superview?.superview as! ChatBubbleCollectionViewCell
        let startingImageFrame = cell.messageImageView.convert(cell.messageImageView.frame, to: nil)
        let imageSize = cell.messageImageView.image?.size

        let zoomingImageView = UIImageView(frame: startingImageFrame)
        zoomingImageView.image = cell.messageImageView.image

        var blackBackgroundView = UIView()

        if gestureState == UIGestureRecognizerState.began {
            if let keyWindow = UIApplication.shared.keyWindow {
                blackBackgroundView = UIView(frame: keyWindow.frame)
                blackBackgroundView.backgroundColor = .black
                blackBackgroundView.alpha = 0

                keyWindow.addSubview(blackBackgroundView)
                keyWindow.addSubview(zoomingImageView)

                UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
                    let screenSize = UIScreen.main.bounds
                    let zoomHeight = screenSize.width / (imageSize?.width)! * (imageSize?.height)!
                    zoomingImageView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: zoomHeight)
                    zoomingImageView.center = self.view.center

                    blackBackgroundView.alpha = 1

                }, completion: nil)
            }

        } else if gestureState == .ended {
            print("Ended")

            UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
            blackBackgroundView.alpha = 0
            zoomingImageView.frame = startingImageFrame

            }, completion: { (completed) in
            blackBackgroundView.removeFromSuperview()
            zoomingImageView.removeFromSuperview()
            })
        }
    }

请注意,当我松开手指触摸时,会打印出打印声明。我想这表明执行代码的地方是正确的。但是,两个removeFromSuperview()函数都没有被调用。上面的代码是我的完整功能代码。

1 个答案:

答案 0 :(得分:0)

您正在长按方法中创建zoomingImageView和blackBackgroundView,而不是在该方法范围之外保留对它的引用。因此,当触摸结束事件发生时,该方法再次执行创建一个新的zoomingImageView和blackBackgroundView,它永远不会添加,然后动画和删除。这就是为什么你没有看到初始视图消失的原因。没有引用这些视图的变量,它们只是屏幕上无法访问的视图。