Created
March 12, 2020 17:05
-
-
Save kuotinyen/e5edae97c7931d4efdd27ff6bde43605 to your computer and use it in GitHub Desktop.
Add UITextField debounce and throttle ability with stupid simple way.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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