Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import UIKit
- class AlertPresenter {
- static let codeValidator = VerificationCodeValidator()
- static func showConfirmationCodeAlert(at vc: UIViewController, title: String, message: String,
- sendCodeAction: @escaping (String) -> ()) {
- let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
- let sendAction = UIAlertAction(title: "Send code", style: .default) { (_) in
- guard let textField = alert.textFields?.first, let text = textField.text else {
- return
- }
- sendCodeAction(text)
- }
- sendAction.isEnabled = false
- let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (alertAction) in
- NotificationCenter.default.removeObserver(vc, name: UITextField.textDidChangeNotification, object: nil)
- }
- alert.addTextField { (textField) in
- textField.placeholder = "Enter code here"
- textField.textColor = .black
- textField.keyboardType = .numberPad
- textField.delegate = codeValidator
- NotificationCenter.default.addObserver(forName: UITextField.textDidChangeNotification, object: textField, queue: OperationQueue.main, using:
- {_ in
- let textCount = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines).count ?? 0
- let textIsNotEmpty = textCount > 3
- sendAction.isEnabled = textIsNotEmpty
- })
- }
- alert.addAction(sendAction)
- alert.addAction(cancel)
- vc.present(alert, animated: true, completion: nil)
- }
- }
- class VerificationCodeValidator: NSObject, UITextFieldDelegate {
- func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
- let allowedCharacters = CharacterSet.decimalDigits
- let characterSet = CharacterSet(charactersIn: string)
- return allowedCharacters.isSuperset(of: characterSet)
- }
- }
- // Usage:
- // AlertPresenter.showConfirmationCodeAlert(at: self, title: "Email verification code",
- // message: "Verification code was sent to your email") { (code) in
- // debugPrint(code)
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement