Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active June 25, 2019 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/346ac828c6e75ac902ac25b9b7ce83f9 to your computer and use it in GitHub Desktop.
Save robertmryan/346ac828c6e75ac902ac25b9b7ce83f9 to your computer and use it in GitHub Desktop.
class ViewController: UIViewController {
@IBOutlet weak var textOTP1: UITextField!
@IBOutlet weak var textOTP2: UITextField!
@IBOutlet weak var textOTP3: UITextField!
@IBOutlet weak var textOTP4: UITextField!
@IBOutlet weak var textOTP5: UITextField!
@IBOutlet weak var textOTP6: UITextField!
@IBOutlet weak var verifyButton: UIButton!
// in addition to outlets above, I'd also add all of the text fields to this outlet collection
@IBOutlet var textFields: [UITextField]!
override func viewDidLoad() {
super.viewDidLoad()
enableButton(false)
// if you wanted to add the targets programmatically, you could do a loop
// like this, though I'd just hook up these actions right in IB
//
// for textField in textFields {
// textField.addTarget(self, action: #selector(textChanges(_:)), for: .editingChanged)
// }
}
@IBAction func didEditingChanged(_ textField: UITextField) {
checkIfWritten()
}
}
private extension ViewController {
func checkIfWritten() {
// rather than if statement with all of the text fields, I'd just iterate through
// the IBOutlet collection we created in IB, and if any of them are empty, then
// disable the button and exit
for textField in textFields where textField.text!.isEmpty {
enableButton(false)
return
}
// if we've gotten here, we know that all the text fields must not be empty, and we can just enable the button
enableButton(true)
}
// since you're calling this from at least two different places, I'd keep it DRY
// and move this into its own method.
func enableButton(_ isEnabled: Bool) {
if isEnabled {
verifyButton.alpha = 1
verifyButton.isEnabled = true
} else {
verifyButton.alpha = 0.2
verifyButton.isEnabled = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment