user4809833
user4809833

Reputation:

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

I have the next function:

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

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

So, I want the next:

For example, user is typing something and stopped in the middle of text. I want to check, if user wrote something and stopped in the middle of typing for 4 seconds to run the function stopped().

I did this:

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")
}

but it runs my NSTimer every time. That's not what I want.

How can I run it just one time? For example to check if user didn't write anything in 4 seconds to run stopped(). Just one time.

Upvotes: 0

Views: 197

Answers (3)

Moritz Schaub
Moritz Schaub

Reputation: 101

Here is a solution for 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")
}

Upvotes: 0

Dulgan
Dulgan

Reputation: 6694

You'll have to keep a reference on your timer and invalidate it whenever textViewDidChange is called, something like that :

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")
}

Upvotes: 1

Leonardo
Leonardo

Reputation: 1750

You need to stop the previous timer with 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)
    }
}

Upvotes: 3

Related Questions