如何从外部访问循环并使其在swift中停止

时间:2016-02-15 21:28:40

标签: ios swift

我使用此功能使文字逐字写入:

extension SKLabelNode {

func setTextWithTypeAnimation(typedText: String, characterInterval: NSTimeInterval = 0.05) {
    text = ""
    self.fontName = "PressStart2P"
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
        for character in typedText.characters {
            dispatch_async(dispatch_get_main_queue()) {
                self.text = self.text! + String(character)
            }
            NSThread.sleepForTimeInterval(characterInterval)
        }
    }
}

并且,如果用户点击屏幕,我想让for循环停止并立即显示完整的文本。

2 个答案:

答案 0 :(得分:0)

我会做这样的事情:

var ignoreSleeper = false    

@IBAction func pressButton(sender: UIButton) {
        ignoreSleeper = true
}

extension SKLabelNode {

func setTextWithTypeAnimation(typedText: String, characterInterval: NSTimeInterval = 0.05) {
    text = ""
    self.fontName = "PressStart2P"
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
        for character in typedText.characters {
            dispatch_async(dispatch_get_main_queue()) {
                self.text = self.text! + String(character)
            }
            if(!ignoreSleeper){
            NSThread.sleepForTimeInterval(characterInterval)
            }
        }
    }
}

编辑,如@Breek已提及

答案 1 :(得分:0)

我建议使用计数器来实现一个微小的NSTimer,以显示要显示的字符数。以重复计数typedText.characters.count和所需的延迟启动计时器,你可以继续(使用一个线程)。增加每个定时器循环的字符计数器数。您可以通过拨打计时器上的invalidate按下按钮随时停止此计时器。

示例

var timer: NSTimer?
var numberOfCharsToPrint = 1
let text = "Hello, this is a test."

func updateLabel() {
    if numberOfCharsToPrint == text.characters.count {
        welcomeLabel.text = text
        timer?.invalidate()
    }

    let index = text.startIndex.advancedBy(numberOfCharsToPrint)
    welcomeLabel.text = text.substringToIndex(index)

    numberOfCharsToPrint++;
}

然后在您希望动画开始时初始化您的计时器。

timer = NSTimer.scheduledTimerWithTimeInterval(0.25, target: self, selector: "updateLabel", userInfo: nil, repeats: true)

您可以使用timer?.invalidate()在任何给定时间使计时器无效/停止。