如何检查用户是否在 4 秒内没有写任何东西?

How to check if user doesn't write anything in 4 seconds?

我有下一个功能:

override func textViewDidChange(textView: UITextView) {
    super.textViewDidChange(textView)

    if textView.text.characters.count == 0 {
        print("stopped")
    } else {
        print("typing")
    }
}

所以,我想要下一个:

例如,用户正在输入内容并停在文本中间。我想检查一下,如果用户写了一些东西并在输入 运行 函数 stopped().

的过程中停了 4 秒

我这样做了:

override func textViewDidChange(textView: UITextView) {
    super.textViewDidChange(textView)

    if textView.text.characters.count == 0 {
        print("stopped")
    } else {
        print("typing")
        let timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "stopped", userInfo: nil, repeats: false)
    }
}

func stopped() {
    print("stopped typing")
}

但它 运行 每次都是我的 NSTimer。那不是我想要的。

如何才能 运行 一次?例如,检查用户是否在 4 秒内没有向 运行 stopped() 写入任何内容。就一次。

您需要使用 invalidate

停止前一个计时器
var timer
override func textViewDidChange(textView: UITextView) {
    super.textViewDidChange(textView)

    if textView.text.characters.count == 0 {
        print("stopped")
    } else {
        timer.invalidate()
        print("typing")
        timer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "stopped", userInfo: nil, repeats: false)
    }
}

你必须在你的计时器上保留一个引用,并在调用 textViewDidChange 时使它无效,就像这样:

var textViewTimer : NSTimer?
override func textViewDidChange(textView: UITextView) {
    super.textViewDidChange(textView)
    textViewTimer.invalidate()
    if textView.text.characters.count == 0 {
        print("stopped")
    } else {
        print("typing")
        textViewTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: "stopped", userInfo: nil, repeats: false)
    }
}

func stopped() {
    print("stopped typing")
}

这里是 Swift 5

的解决方案
var textViewTimer: Timer?
override func textViewDidChange(textView: UITextView) {
    textViewTimer.invalidate()
    print("typing")
    textViewTimer = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(typingStopped), userInfo: nil, repeats: false)
    }
} 
@objc func typingStopped() {
    print("stopped")
}