I am using the code below to keep an imageView/player inside the screen. The code works for the most part, but at times, the player flies off the screen and completely disappears. I am using UIPanGestureRecognizer to move the image around the screen. Using Swift and UIKit, how do I keep the image within the bounds of the screen one hundred percent of the time without the image flying off of the screen?
@objc func panFunction(_ sender: UIPanGestureRecognizer) {
if sender.state == .began || sender.state == .changed {
let translation = sender.translation(in: sender.view)
let changeX = (sender.view?.center.x)! + translation.x
let changeY = (sender.view?.center.y)! + translation.y
let senderWidth = sender.view!.bounds.width / 2
let senderHeight = sender.view!.bounds.height / 2
sender.view?.center = CGPoint(x: changeX, y: changeY)
if changeX <= senderWidth {
sender.view!.center = CGPoint(x: senderWidth, y: sender.view!.center.y + translation.y)
}else
if changeX >= self.view.bounds.maxX - senderWidth {
sender.view!.center = CGPoint(x: self.view.bounds.maxX - senderWidth, y: sender.view!.center.y + translation.y)
}
if changeY <= senderHeight {
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: senderHeight)
}else
if changeY >= self.view.bounds.maxY - senderHeight {
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: self.view.bounds.maxY - senderHeight)
}else{
sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y)
}
sender.setTranslation(CGPoint.zero, in: self.view)