Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ManagedTextField: UITextField {
- weak var textFieldManagerDelegate : TextFieldManger?
- override init(frame: CGRect) {
- super.init(frame: frame)
- }
- private var previousValue : String?
- private var timer = Timer()
- required init?(coder aDecoder: NSCoder) {
- super.init(coder: aDecoder)
- }
- override func draw(_ rect: CGRect) {
- super.draw(rect)
- commonInit()
- }
- private func commonInit() {
- NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: self, queue: nil, using: {
- [weak self]
- notification in
- guard let strongSelf = self else { return }
- guard let object = notification.object as? ManagedTextField, object == self else { return }
- if strongSelf.previousValue != strongSelf.text {
- strongSelf.timer.invalidate()
- strongSelf.timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false, block: { timer in
- strongSelf.textFieldManagerDelegate?.makeApiRequest(withValue: strongSelf.text)
- })
- if let newCount = strongSelf.text?.count,
- let oldCount = strongSelf.previousValue?.count {
- if newCount < oldCount {
- strongSelf.timer.invalidate()
- }
- }
- }
- strongSelf.previousValue = strongSelf.text
- })
- }
- }
Add Comment
Please, Sign In to add comment