向右动画UIScrollView

时间:2016-10-14 18:20:52

标签: swift uiviewcontroller uiscrollview uiimageview

如何制作动画,以均匀的速度向右移动/滚动可见图像部分?或者更确切地说:如何向右侧动画UIScrollView?

示例:图像宽度为4968像素。该图像用作全屏背景图像。开头只能看到4968px(图像宽度)的前1242px。可见图像部分应以均匀的速度向右移动。在任何时候,都可以看到1242像素的图像。当到达图像的末尾时,应该迭代这个过程。

Visualisation of my question

到目前为止,这是我的代码。理解我想要完成的内容是没有用的,因为它不完整,但你看到我在函数更新中使用它等等。

override func update(_ currentTime: TimeInterval) {
    if gameStarted == true {
        enumerateChildNodes(withName: "background", using: ({
            (node, error) in

            let bg = node as! SKSpriteNode

            bg.position = CGPoint(x: bg.position.x - 2, y: bg.position.y)
            }
        }))
    }
}

2 个答案:

答案 0 :(得分:2)

您可以为其contentOffset属性设置动画

@IBOutlet weak var scrollView: UIScrollView!

override func viewDidAppear(animated: Bool) {
    // This code scrolls to the point (x: 4000, y:0) in 5 seconds
    UIView.animateWithDuration(5) { [unowned self] in
        self.scrollView.contentOffset = CGPoint(x: 4000, y: 0)
    }
}

答案 1 :(得分:2)

如果您希望游戏背景以均匀的速度移动,则根本不需要UIScrollView

但是,要使其顺利迭代,您必须同时保留两张图像。

var imageWidth : Float = 4968
var viewPortWidth : Float = 1242 
var velocity : Float = 10
var currentNodeIndex : Int = 0
let backgrounds : [String] = ["background0", "background1"]
var currentNodeName : String {
    get {
        return backgrounds[currentNodeIndex]
    }
}

func setup() {
    node : SKNode = SKSpriteNode(imageNamed:"backgroundImage")
    node.name = "background0"
    node1 : SKNode = SKSpriteNode(imageNamed:"backgroundImage")
    node1.name = "background1"
    addChild(node)
    addChild(node1)
    node.position = CGPoint(x: imageWidth, y: 0)
    node1.position = CGPoint(x: 0, y: 0)
}

override func update(_ currentTime: TimeInterval) {
    if gameStarted == true {
        backgrounds.forEach {
            enumerateChildNodes(withName: $0, using: {(node, error) in
                node.position = CGPoint(x: node.position.x - velocity, y: node.position.y)
            })
        }
    }
}

private func rollImageAroundIfNeeded() {
    if needsRollImages() {
        rollImagesAround()
    }
}

private func needsRollImages() -> Bool {
    node : SKNode = childNode(withName:currentNodeName)!
    return node.position.x < 2 * (screenWidth - imageWidth)
}

private func rollImageAround() {
    node : SKNode = childNode(withName:currentNodeName)!
    node.position = CGPoint(x: node.position.x + 2 * imageWidth, y: node.position.y)
    currentNodeIndex = (currentNodeIndex + 1) % 2
}

这个想法是你不断地将两个图像位置向左移动,并在某个阈值处将“左图像”包裹在右侧。