0

I am creating an iOS app in swift which required multiple items (6) of data to be provided by the user. I have implemented this through text fields. All of the data needs the same basic checking done on it. Ideally I'd like to be able to iterate over some form of collection - perhaps an array of text fields - so that I don't have to repeat the same code to check the data from different fields.
Is there a way to bind the text fields, or their .text properties to an array or similar?

form

Adam
  • 26,549
  • 8
  • 62
  • 79
  • Take a look at [SwiftForms](https://github.com/ortuman/SwiftForms). Not sure if that is exactly what you are looking for but still worth taking a look. – Adam Jan 03 '16 at 10:45

2 Answers2

1

If you’re using Interface Builder, you can create an IBOutlet collection and bind all your text fields to it. It will be an array of text fields.

See this related question (using UIImageView, but the principles are the same).

In Swift, it looks like this:

@IBOutlet var textFields: [UITextField]!

… and you connect it up in Interface Builder like a normal outlet, but you can connect multiple fields to it.

If you’re not using Interface Builder, you can just put them in an array:

let textFields = [textField1, textField2, textField3]

… and then in either case (Interface Builder or not) you can iterate over the array to do things with the text fields, like configure them or check the text property:

for textField in textFields {
    // Do things to textField
}
Community
  • 1
  • 1
jbg
  • 4,903
  • 1
  • 27
  • 30
0

You can create an array of textfields and then iterate through the textfields

example:

let textfieldCollection = [textfield1,textfield2,textfield3]

for tf in textfieldCollection {
   //validation code
}