XCode 6-在循环中延迟迭代?

XCode 6-在循环中延迟迭代?,xcode,swift,Xcode,Swift,我正在使用while循环测试一个基本动画。当用户触摸开始按钮时,每次单击按钮都会随机出现一个图像。然后,我将相同的代码放在一个while循环中,图像似乎没有移动。我认为它只是在迭代过程中移动得太快,因此似乎没有移动。那么,有没有一种简单或其他的方法,可以延迟循环的速度,这样我就可以看到某种程度的转换?我认为循环的速度就是这样做的,因为文本会立即输出到标签,因此我知道循环至少在工作。这是我所拥有的 @IBAction func btnStart(sender: AnyObject) {

我正在使用while循环测试一个基本动画。当用户触摸开始按钮时,每次单击按钮都会随机出现一个图像。然后,我将相同的代码放在一个while循环中,图像似乎没有移动。我认为它只是在迭代过程中移动得太快,因此似乎没有移动。那么,有没有一种简单或其他的方法,可以延迟循环的速度,这样我就可以看到某种程度的转换?我认为循环的速度就是这样做的,因为文本会立即输出到标签,因此我知道循环至少在工作。这是我所拥有的

@IBAction func btnStart(sender: AnyObject) {

    isMoving = true
    var i = 0
    while (i != 200) //arbitrary number of iterations chosen for this example
    {
        var x = arc4random_uniform(400)
        var y = arc4random_uniform(400)
        myButton.center = CGPointMake(CGFloat(x), CGFloat(y));
        ++i
        lblHitAmount.text = String(i) //200 appears instantaneously in label, loop is working
   }
 }  
编辑:


因此,要理解为什么会出现这种行为,您需要理解运行循环的概念。每个应用程序都有一个本质上是无限循环的运行循环。循环的每一次迭代都会做很多事情。其中两个主要任务是处理事件(如点击按钮)和更新GUIGUI在每次运行循环中仅更新一次

事件处理代码(用于点击btnStart)在单个运行循环迭代中运行。无论循环延迟多长时间(比如10分钟),GUI都将保持冻结状态,直到它完成,然后只显示文本设置为的最后一个值。这就是为什么应用程序和程序会冻结。它们在运行循环的单个迭代中运行,不允许执行返回到更新GUI

如果您想定期更新文本,您应该查看。您可以设置一个每X秒重复一次的计时器,每次启动计时器时,它将在运行循环的不同迭代中执行,从而允许GUI使用中间值进行更新:

@IBAction func btnStart(sender: AnyObject) {
    NSTimer.scheduleTimerWithTimeInterval(0.5, target: self, selector: "updateText:", userInfo: nil, repeats: false) 
}

func updateText(timer: NSTimer) {
    // do something to update lblHitAmount.text
    // if you want to execute this again run:
    NSTimer.scheduleTimerWithTimeInterval(0.5, target: self, selector: "updateText:", userInfo: nil, repeats: false) 
    // if you are done with the "loop" don't call scheduleTimerWithTimeInterval again.
}

非常感谢。多亏了你的建议,我尝试了一些事情,并取得了一些进展。然而,不管我如何努力,不管我如何实现,它似乎只会迭代两次。请参阅上面我编辑的部分。再次提前感谢。@MitchKrendell尝试关闭“重复”,并在toLabel中每次安排一个新的计时器。而且,我甚至不理解您代码的上下文。为什么在之前的一段时间内,您仍在增加
计数器
?IBAction中是否嵌入了toLabel函数?
@IBAction func btnStart(sender: AnyObject) {
    NSTimer.scheduleTimerWithTimeInterval(0.5, target: self, selector: "updateText:", userInfo: nil, repeats: false) 
}

func updateText(timer: NSTimer) {
    // do something to update lblHitAmount.text
    // if you want to execute this again run:
    NSTimer.scheduleTimerWithTimeInterval(0.5, target: self, selector: "updateText:", userInfo: nil, repeats: false) 
    // if you are done with the "loop" don't call scheduleTimerWithTimeInterval again.
}