ios - 我的代码似乎运行得太快

标签 ios swift nstimer

我正在编写一个 Simon 风格的内存游戏,程序向用户显示当前要记住的东西列表的游戏阶段似乎立即运行。

想法是遍历列表(在代码中,我将每个项目中的 1 个作为调试数据)并在设定的时间段内更改屏幕上的颜色,然后移至下一个。

我想对内存数组中的每个项目使用,然后调用一个简单的过程来检查它是哪一个,然后在设定的时间段内改变颜色,然后恢复到原来的颜色。

如果我在测试更改颜色(灰色)和原始颜色之间放置中断,我在此处添加的代码将起作用。但出于某种原因,计时器似乎不太工作。

有什么想法吗?

import UIKit
import Foundation

var gameisrunning = false
var playererror = false
var memoryArray = [Int]()
var currentScore = 0

var timer = NSTimer()

class ViewController: UIViewController {

    @IBAction func startGameButton(sender: UIButton) {

        if gameisrunning == false {

            gameisrunning = true
            memoryArray.append(1) //for debug
            memoryArray.append(2) //for debug
            memoryArray.append(3) //for debug
            memoryArray.append(4) //for debug
            print(memoryArray) //for debug
            gameStart()

        } else {


        }

    }


    //these are to be implemented once i get the showing sequence sorted.

    @IBAction func redButton(sender: UIButton) {

    }

    @IBAction func greenButton(sender: UIButton) {

    }

    @IBAction func yellowButton(sender: UIButton) {

    }

    @IBAction func blueButton(sender: UIButton) {

    }

    @IBOutlet weak var redLabel: UILabel!
    @IBOutlet weak var greenLabel: UILabel!
    @IBOutlet weak var yellowLabel: UILabel!
    @IBOutlet weak var blueLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!

    func addAnotherItemToMemory () {

        // adds another item to the memory

        memoryArray.append(Int(arc4random_uniform(4)+1))
    }

    func gameStart () {

        // main body of game
        showPlayerTheMemory()
    }


    func showPlayerTheMemory () {

        // go through list and highlight the colors one at a time

        for eachItem in memoryArray {
            self.showColor(eachItem)
        }
    }


    func pauseForAWhile(length: Double) {

        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: nil , userInfo: nil, repeats: false)
        timer.invalidate()

    }


    func showColor(buttonItem: Int) {

        //check to see which color, change to grey (test color) and back to original after a set time.

        if buttonItem == 1  {

            self.redLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            self.redLabel.backgroundColor = UIColor.redColor()
            print(buttonItem) //for debug

        } else if buttonItem == 2 {

            self.greenLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            greenLabel.backgroundColor = UIColor.greenColor()
            print(buttonItem) //for debug

        } else if buttonItem == 3 {

            self.yellowLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            yellowLabel.backgroundColor = UIColor.yellowColor()
            print(buttonItem) //for debug

        } else if buttonItem == 4 {

            self.blueLabel.backgroundColor = UIColor.grayColor()
            pauseForAWhile(2)
            blueLabel.backgroundColor = UIColor.blueColor()
            print(buttonItem) //for debug

        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

新的相关代码更改为:

func colorChange (){

    self.redLabel.backgroundColor = UIColor.redColor()
    self.blueLabel.backgroundColor = UIColor.blueColor()
    self.yellowLabel.backgroundColor = UIColor.yellowColor()
    self.greenLabel.backgroundColor = UIColor.greenColor()
}

func showColor(buttonItem: Int, length: Double) {

    //check to see which color, change to grey (test color) and back to original after a set time.

    if buttonItem == 1  {

        self.redLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 2 {

        self.greenLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 3 {

        self.yellowLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    } else if buttonItem == 4 {

        self.blueLabel.backgroundColor = UIColor.grayColor()
        timer = NSTimer.scheduledTimerWithTimeInterval(length, target:self, selector: ("colorChange") , userInfo: nil, repeats: false)
        print(buttonItem) //for debug

    }
}

我整天都在挠头试图解决这个让我感到困惑的问题。我已经在下面复制了新的最新代码,请丢弃上面的代码。

我有四个标签,颜色分别为红色、蓝色、绿色和黄色。内部包含 4 3 2 1 测试数据的数组需要遍历每个项目 - 更改标签的颜色 x 秒,然后将其恢复为正常颜色。我试过 NSTimer,我试过附加代码中的当前延迟。我是否遗漏了一些关于代码放置位置的信息 - 它应该在 viewdidload 下吗???我已经尝试了循环,当前的代码示例显示了 switch,以防它的行为不同——它没有!!

基本上发生的是所有标签同时变灰(现在测试颜色)然后在 x 秒延迟后全部变为原始颜色。

在我发疯之前我需要一些帮助。老实说,我知道这是一些基本的东西,但我就是想不通。

import UIKit
import Foundation

var gameisrunning = false
var playererror = false
var memoryArray = [Int]()
var currentScore = 0

class ViewController: UIViewController {

    @IBAction func startGameButton(sender: UIButton) {

        if gameisrunning == false {

            gameisrunning = true
            memoryArray.append(4) //for debug
            memoryArray.append(3) //for debug
            memoryArray.append(2) //for debug
            memoryArray.append(1) //for debug
            print(memoryArray) //for debug
            gameStart()

        } else {

        }
    }


    //these are to be implemented once i get the showing sequence sorted.

    @IBAction func redButton(sender: UIButton) {
    }
    @IBAction func greenButton(sender: UIButton) {
    }
    @IBAction func yellowButton(sender: UIButton) {
    }
    @IBAction func blueButton(sender: UIButton) {
    }

    @IBOutlet weak var redLabel: UILabel!
    @IBOutlet weak var greenLabel: UILabel!
    @IBOutlet weak var yellowLabel: UILabel!
    @IBOutlet weak var blueLabel: UILabel!
    @IBOutlet weak var scoreLabel: UILabel!

    func addAnotherItemToMemory () {
        // adds another item to the memory
        memoryArray.append(Int(arc4random_uniform(4)+1))
    }

    func gameStart () {
        // main body of game
        showPlayerTheMemory()
    }

    func delayProg (){
        //attempt 100093287492 to get a delay in program
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2.0 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.blueLabel.backgroundColor = UIColor.blueColor()
            self.yellowLabel.backgroundColor = UIColor.yellowColor()
            self.greenLabel.backgroundColor = UIColor.greenColor()
            self.redLabel.backgroundColor = UIColor.redColor()

        }
    }

    func showPlayerTheMemory () {

        // go through list and highlight the colors one at a time

        for var i=0; i <= memoryArray.count-1; i++ {
            self.showColor(memoryArray[i])
        }
    }


    func showColor(buttonItem: Int) {

        //check to see which color, change to grey (test color) and back to original after a set time.

        switch (buttonItem) {

        case 1:
            self.redLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 2:
            self.greenLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 3:
            self.yellowLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        case 4:
            self.blueLabel.backgroundColor = UIColor.grayColor()
            delayProg()
            print(buttonItem) //for debug
        default:
            print("error")
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

最佳答案

这是一个正确实现 NSTimer() 的例子

var myTimer = NSTimer()

func startTimer() {
    myTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: "myFunction", userInfo: nil, repeats: true)
}

func myFunction() {
myTimer.invalidate()
    //do other stuff
}
//the selector is "myFunction", this will be the name of the function that you wish to call every time the timer reaches its specified intervl
//the interval in this case is 10 seconds. In my experience NSTimer is good down to the second but is not precise enough beyond that
//repeats: true ... this will tell the timer to repeat its action consistently firing the selector each time the given time interval is reached. If repeat is set to false then the timer only fires once
//use myTimer.invalidate to stop the timer and to stop calling the selector.

一定要使您的计时器或设置repeats: false 以确保它不会永远持续下去。确保您的选择器的拼写与您的功能完全相同。如果您的函数是 func myFunction(),那么选择器应该是 "myFunction"。确保指定有效的时间间隔,以秒为单位。

关于ios - 我的代码似乎运行得太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35132606/

相关文章:

ios - 使用 ARKit 加载的 3d 文件有大小限制吗?

swift - 来自 [字符串 : Any] to "Key = Value" String in Swift

ios - 我如何访问更改的字段或更改前的旧数据?

xcode - ViewController.Type 没有名为的成员

iphone - scheduledTimerWithTimeInterval vs performselector with delay with iOS 5.0

android - 如何每 X 秒运行一次方法

ios - 如何根据设备的高度和宽度缩放 UIImage 以适合屏幕

iphone - while (sqlite3_step(statement1) == SQLITE_ROW) 不工作,即使两个值在 iPhone 中相等

ios - Xcode 7 Beta 5,UITableViewCells subview 被裁剪出 ContentView

ios - 以编程方式一个接一个地关闭 SwiftUI View 不起作用