在 Swift 中将图像保留在屏幕上

Keeping an image on screen in Swift

我有一个游戏,我使用 UISwipeGestureRecognizer 移动屏幕。我想弄清楚如何制作它,以便我滑动的图像不能离开屏幕。我在互联网上四处张望,却找不到任何东西。

这是我的刷卡方法:

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()
   }
}

这是我的 moveBackground 方法:

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

到目前为止,我唯一尝试过的就是检查视图是否位于某个位置,如果是,则将其删除,但这没有用。我将该代码添加到滑动方法中。

如果您在此处 post 您的 class 代码,将会非常有帮助,这样我们就可以更具体地帮助您。

顺便说一句,每次调用该函数时,您都应该检查对象的位置,然后再移动它,并牢记它的大小。

假设您有一个纸牌游戏,您正在棋盘上刷卡。 为避免将卡片从板上刷掉(离开屏幕),您必须执行以下操作:

// 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
        // ...
    }
}

希望对您有所帮助! 问候。