等待鼠标单击Inside While Loop

时间:2016-03-22 19:40:05

标签: swift macos sprite-kit

我正在使用Sprite Kit进行OS X项目,我无法弄清楚如何暂停while循环直到鼠标单击。我想要的是这样的:

while (i < 50){
    print(i)
    i += 1
    waitForMouseClick()
}

1 个答案:

答案 0 :(得分:1)

我使用GCD后台队列和信号量解决了它。对于阅读此内容的其他人可能会有帮助。

// CREATE A BACKGROUND QUEUE AND SEMAPHORE
let bgQueue = dispatch_queue_create("myQueue", nil)
let semaphore = dispatch_semaphore_create(0) 

override func didMoveToView(view: SKView) {
    //DISPATCH CODE BLOCK TO QUEUE
    dispatch_async(bgQueue, {
        //THIS WILL GRAB YOUR SEMAPHORE
        dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_NOW)
        var i: Int = 0
        while (i<50){
            i += 1
            //BLOCK
            dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER)
            print(i)
        }
    })
}

override func mouseDown(theEvent: NSEvent) {
    //RELEASE SEMAPHORE
    dispatch_semaphore_signal(semaphore)
}