class Form {
@IBOutlet var fieldsToClear: [UITextField]! //Outlet collection of 20 textfields of the form screen
var allFieldsAreEmpty : Bool = false // variable to change when ever any of the textfield changes
}
I have 20 textfields in a view controller.I have created an outletCollection for all the textfields. I want to know whether it's possible to observe all textfields and check whether any of them are empty or not and so on without using any event outlet for all the textfields one by one which could make the view controller messy.
All i want is to check all textfields and change the allFieldsAreEmpty variables accordingly.
Checking if all text fields are empty:
Here's one way:
// All are empty if it's true.
fieldsToClear.compactMap { $0.text }.allSatisfy { $0.isEmpty }
.compactMap { $0.text }
gets you all non-nil text values from all text fields. And .allSatisfy { $0.isEmpty }
checks whether all texts are empty.
Observing text fields:
To observe changes in a text field, you can assign a delegate to it:
textField.delegate = // ... Something that conforms to UITextFieldDelegate
In your case you can assign the same delegate to all text fields. For instance, in viewDidLoad
:
fieldsToClear.forEach { $0.delegate = /* your delegate */ }
UITextFieldDelegate
has methods to track text editing. E.g., textFieldDidEndEditing(_:)
is called whenever text editing in a text field is ended. If this is a right moment for your check you can insert it there:
func textFieldDidEndEditing(_ textField: UITextField) {
allFieldsAreEmpty = fieldsToClear.compactMap { $0.text }.allSatisfy { $0.isEmpty }
}