Skip to content

Instantly share code, notes, and snippets.

@kuotinyen
Created March 12, 2020 17:05
Show Gist options
  • Save kuotinyen/e5edae97c7931d4efdd27ff6bde43605 to your computer and use it in GitHub Desktop.
Save kuotinyen/e5edae97c7931d4efdd27ff6bde43605 to your computer and use it in GitHub Desktop.
Add UITextField debounce and throttle ability with stupid simple way.
extension UITextField {
private static var _texts = [String: [String]]()
var texts: [String] {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UITextField._texts[tmpAddress] ?? []
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UITextField._texts[tmpAddress] = newValue
}
}
private static var _textClosureBag = [String: [(String) -> ()]]()
var textClosureBag: [(String) -> ()] {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return UITextField._textClosureBag[tmpAddress] ?? []
}
set {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
UITextField._textClosureBag[tmpAddress] = newValue
}
}
func debounce(on queue: DispatchQueue = .main, by timeInterval: TimeInterval, closure: @escaping (String) -> ()) {
texts.append(self.text!)
textClosureBag.append(closure)
queue.asyncAfter(deadline: .now() + timeInterval) {
guard let lastClosure = self.textClosureBag.last, let lastText = self.texts.last else { return }
lastClosure(lastText)
self.texts.removeAll()
self.textClosureBag.removeAll()
}
}
func throttle(on queue: DispatchQueue = .main, by timeInterval: TimeInterval, closure: @escaping (String) -> ()) {
texts.append(self.text!)
textClosureBag.append(closure)
queue.asyncAfter(deadline: .now() + timeInterval) {
guard let firstClosure = self.textClosureBag.first, let firstText = self.texts.first else { return }
firstClosure(firstText)
self.texts.removeAll()
self.textClosureBag.removeAll()
}
}
}
inputTextField.debounce(by: 2) { (text) in
DispatchQueue.main.async {
print("text -> \(text)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment