How to loop through view outlets in a UIViewController with Swift?

This is what Outlet Collections are for. Drag all your textfields in the same Outlet Collection in InterfaceBuilder and create an @IBOutlet to that collection in your class file:

To create the outlet collection in InterfaceBuilder, ctrl-drag from the first UITextField to your class file in the assistant editor. Then choose Outlet Collection:

enter image description here

ctrl-drag the next UITextField on that @IBOutlet to add it to the collection:

enter image description here

Repeat that for all your textFields.

@IBOutlet var textFields: [UITextField]!

func checkTextFields() {
    for textField in self.textFields {
        ... // do your checks
    }
}

Leave a Comment