I am attempting to remove an imageView and a backgroundView from the superView after the longPress has ended. I have consulted the solutions here and here which should have worked. What I want to achieve is that when I longPress the imageView in my collectionViewCell, it zooms out the image, and when I release the touch, the imageView zooms back to the position of the cell, and then removeFromSuperview()
My current code did not animate and did not remove the blackBackgroundView and zoomingImageView from the view in the .ended
block. Both views stayed in view.
@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()
})
}
}
Note that when I release the finger touch, the print statement gets printed. I suppose that indicates that the place to execute the code is correct. However, both removeFromSuperview()
functions did not get called. Above code is my full function code.