Skip to content

Instantly share code, notes, and snippets.

@SergLam
Created August 6, 2019 14:57
Show Gist options
  • Save SergLam/652db7cec81e7e5a5c0fda070d300a12 to your computer and use it in GitHub Desktop.
Save SergLam/652db7cec81e7e5a5c0fda070d300a12 to your computer and use it in GitHub Desktop.
Alert Controller + TextField + Validation
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)
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment