swift - 如何每 (x) 秒从数组中获取随机字符串 (SWIFT 3)(SPRITEKIT)

标签 swift sprite-kit swift3

我想知道如何每隔 (x) 秒从数组中获取一个随机字符串并将其显示到 SKLabelNode 中。在这种情况下,每 3 秒一次。

到目前为止,这段代码从我的数组中显示了一个随机字符串,我只需要添加一个计时器,以便每隔几秒打印一个不同的字符串。

我想要打印随机字符串的 SKLabelNode 是“colorClick”

这是数组本身:让 whichcolortoclick = ["Blue Box", "Red Box", "Pink Box", "Yellow Box"]

    let randomIndex = Int(arc4random_uniform(UInt32(whichcolortoclick.count)))
        colorClick.text = (whichcolortoclick[randomIndex])

总而言之,我真正想要的是添加一个计时器,并每隔几秒从数组中显示一个随机字符串。然后,将其显示在 colorClick LabelNode 中。

最佳答案

您可以为此使用 SKAction repeat forever(不要在 SpriteKit 中使用 NSTimers)。

像这样

override func didMove(to view: SKView) {

    let actionUpdateLabel = SKAction.run { [weak self] in
         self?.updateTextLabel()
    }
    let actionDelay = SKAction.wait(forDuration: 3) // swap this with the update action if you want to have the delay first.
    let sequenceUpdateLabel = SKAction.sequence([actionUpdateLabel, actionDelay])
    run(SKAction.repeatForever(sequenceUpdateLabel))
}

func updateTextLabel() {
    let randomIndex = Int(arc4random_uniform(UInt32(whichcolortoclick.count)))
    colorClick.text = (whichcolortoclick[randomIndex])
}

希望对你有帮助

关于swift - 如何每 (x) 秒从数组中获取随机字符串 (SWIFT 3)(SPRITEKIT),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42215244/

相关文章:

ios - SpriteKit,把一个进程放在另一个核心上?

objective-c - 在 Swift 中传递 @protocol 类型

swift - '+ =' produces ' ()'。我如何从闭包中返回增量值

swift - 无法在 swift 中使用 getter 和 setter 设置变量本身

Swift:在 nstimer 倒计时结束时过渡到新的 View Controller

SwiftUI TabView + NavigationView 导航栏不显示

ios - 场景暂停时 GameplayKit 不暂停

ios - Swift异步加载报错

ios - 动态创建菜单但使用相同的 View Controller [PagingMenuController]

ios - 使用 Firebase 电子邮件验证链接登录