Detect when user pauses / pauses text input in Swift

I dug around stackoverflow and found a solution that I converted to Swift, it doesn't seem to work, and the selector is still executing.

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { self.filter.searchTerm = self.searchBar.text NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "getHints", object: nil) NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "getHints", userInfo: nil, repeats: false) } 

Is there a better way to do this fast? Thanks!

+6
source share
1 answer

UPDATE 2016/09/01:

We can use NSTimers or (starting with Swift 2.0) NSObject performSelector and friends.

Aproach 1: performSelector

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { NSObject.cancelPreviousPerformRequests( withTarget: self, selector: #selector(ViewController.getHintsFromTextField), object: textField) self.perform( #selector(ViewController.getHintsFromTextField), with: textField, afterDelay: 0.5) return true } func getHintsFromTextField(textField: UITextField) { print("Hints for textField: \(textField)") } 

Approach 2: NSTimer

 var timer: NSTimer? = nil func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { timer?.invalidate() timer = Timer.scheduledTimer( timeInterval: 0.5, target: self, selector: #selector(ViewController.getHints), userInfo: ["textField": textField], repeats: false) return true } func getHints(timer: Timer) { var userInfo = timer.userInfo as! [String: UITextField] print("Hints for textField: \(userInfo["textField"])") } 

Note. I pass the textField to the delayed function. This is not always required, but it can make your life easier when textField not easy to access or when working with various text fields.

How is the NSTimer approach different from performSelector ?

When you call performSelector , (with a fast target it’s always self ), but when using NSTimer target is NOT saved, This means that if you use NSTimer s, you must make sure that the target (in this case self ) is alive at the time the timer starts. Otherwise, it will fail.

(BTW: performSelector uses NSTimer internally πŸ˜€)

If you are interested in GCD timers, this is the beginning of a good start: maicki / TimerWithGCD.md

+26
source

Source: https://habr.com/ru/post/985562/


All Articles