Search code examples
swiftuiswipegesturerecognizer

Keeping an image on screen in Swift


I have a game where I use a UISwipeGestureRecognizer to move the screen. I am trying to figure out how to make it so that the image that I am swiping cannot move off the screen. I have looked around the internet and have not been able to find anything.

Here is my swipe method:

func swipedRight(sender: UISwipeGestureRecognizer) {
   timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("moveBackground"), userInfo: nil, repeats: true)

   if imageView.frame.origin.x > 5000 {
      imageView.removeFromSuperview()
   }
}

Here is my moveBackground method:

func moveBackground() {
    self.imageView.frame = CGRect(x: imageView.frame.origin.x - 100, y:     imageView.frame.origin.y, width: 5500, height: UIScreen.mainScreen().bounds.height)
}

The only things I have tried so far is to check if the view is in a certain position and remove it if it is but that hasn't worked. I added that code to the swipe method.


Solution

  • It will be very helpful if you post your class code here, so we can be more specific helping you.

    By the way, you should check the object position each time the function is called, before move it, taking in mind its size.

    Lets say you have a playing cards game and you are swiping a card along the board. To avoid swiping the card off the board (off the screen) you will have to do something like this:

    // I declare the node for the card with an image
    var card = SKSpriteNode(imageNamed: "card")
    
    // I take its size from the image size itself
    card.physicsBody = SKPhysicsBody(rectangleOfSize: card.size)
    
    // I set its initial position to the middle of the screen and add it to the scene
    card.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)
    self.addChild(card)
    
    // I set the min and max positions for the card in both X and Y axis regarding the whole scene size.
    // Fit it to your own bounds if different
    let minX = card.size.width/2
    let minY = card.size.height/2
    let maxX = self.frame.size.width - card.size.height/2
    let maxY = self.frame.size.width - card.size.height/2
    
    // HERE GOES YOUR SWIPE FUNCTION
    func swipedRight(sender: UISwipeGestureRecognizer) {
        // First we check the current position for the card
        if (card.position.x <= minX || card.position.x >= maxX || card.position.y <= minY || card.position.y >= maxY) {
            return
        }
        else {
            // ... 
            // YOUR CODE TO MOVE THE ELEMENT
            // ...
        }
    }
    

    I hope this helps! Regards.