2

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)
Alicia
  • 41
  • 5
  • Can you elaborate a bit on when the view flies off screen? – l_priebe Feb 28 '19 at 16:25
  • I am moving the player around the screen with my finger using pan gesture recognizer. I may be moving the player too quickly when it flies off the screen. I can flick the image off the screen using a hard gesture with my finger. If I move the player carefully around the screen, the image stays within bounds. – Alicia Mar 01 '19 at 18:27

0 Answers0