Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. import UIKit
  2.  
  3. class AlertPresenter {
  4.  
  5. static let codeValidator = VerificationCodeValidator()
  6.  
  7. static func showConfirmationCodeAlert(at vc: UIViewController, title: String, message: String,
  8. sendCodeAction: @escaping (String) -> ()) {
  9.  
  10. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  11.  
  12. let sendAction = UIAlertAction(title: "Send code", style: .default) { (_) in
  13. guard let textField = alert.textFields?.first, let text = textField.text else {
  14. return
  15. }
  16. sendCodeAction(text)
  17. }
  18. sendAction.isEnabled = false
  19.  
  20. let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (alertAction) in
  21. NotificationCenter.default.removeObserver(vc, name: UITextField.textDidChangeNotification, object: nil)
  22. }
  23.  
  24. alert.addTextField { (textField) in
  25.  
  26. textField.placeholder = "Enter code here"
  27. textField.textColor = .black
  28. textField.keyboardType = .numberPad
  29. textField.delegate = codeValidator
  30.  
  31. NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main, using:
  32. {_ in
  33.  
  34. let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).count ?? 0
  35. let textIsNotEmpty = textCount > 3
  36.  
  37. sendAction.isEnabled = textIsNotEmpty
  38. })
  39. }
  40. alert.addAction(sendAction)
  41. alert.addAction(cancel)
  42.  
  43. vc.present(alert, animated: true, completion: nil)
  44. }
  45.  
  46. }
  47.  
  48. class VerificationCodeValidator: NSObject, UITextFieldDelegate {
  49.  
  50. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  51. let allowedCharacters = CharacterSet.decimalDigits
  52. let characterSet = CharacterSet(charactersIn: string)
  53. return allowedCharacters.isSuperset(of: characterSet)
  54. }
  55.  
  56. }
  57.  
  58. // Usage:
  59. // AlertPresenter.showConfirmationCodeAlert(at: self, title: "Email verification code",
  60. // message: "Verification code was sent to your email") { (code) in
  61. // debugPrint(code)
  62. // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement