Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm wondering, if it's possible to loop through all the outlets of a UIViewController with Swift.

Specifically, I want to check if every textfield is filled by the user.

like image 680
twofish Avatar asked Mar 20 '15 13:03

twofish


2 Answers

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
    }
}
like image 177
zisoft Avatar answered Nov 16 '22 21:11

zisoft


I think you have to manually do it, or add them to array and loop through that array or you can loop through all subviews of your view and check if it's textfield.

for view in self.view.subviews as [UIView] {
    if let textField = view as? UITextField {
        if textField.text == "" {
            // textfield is empty
            return
        }
    }
}
like image 26
IxPaka Avatar answered Nov 16 '22 22:11

IxPaka