IbrahimHassan

Untitled

Nov 6th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class ManagedTextField: UITextField {
  2.  
  3. weak var textFieldManagerDelegate : TextFieldManger?
  4.  
  5. override init(frame: CGRect) {
  6. super.init(frame: frame)
  7. }
  8.  
  9. private var previousValue : String?
  10.  
  11. private var timer = Timer()
  12.  
  13. required init?(coder aDecoder: NSCoder) {
  14. super.init(coder: aDecoder)
  15. }
  16.  
  17. override func draw(_ rect: CGRect) {
  18. super.draw(rect)
  19. commonInit()
  20. }
  21.  
  22. private func commonInit() {
  23. NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: self, queue: nil, using: {
  24. [weak self]
  25. notification in
  26. guard let strongSelf = self else { return }
  27. guard let object = notification.object as? ManagedTextField, object == self else { return }
  28. if strongSelf.previousValue != strongSelf.text {
  29. strongSelf.timer.invalidate()
  30. strongSelf.timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false, block: { timer in
  31. strongSelf.textFieldManagerDelegate?.makeApiRequest(withValue: strongSelf.text)
  32. })
  33. if let newCount = strongSelf.text?.count,
  34. let oldCount = strongSelf.previousValue?.count {
  35. if newCount < oldCount {
  36. strongSelf.timer.invalidate()
  37. }
  38. }
  39. }
  40. strongSelf.previousValue = strongSelf.text
  41. })
  42. }
  43.  
  44. }
Add Comment
Please, Sign In to add comment