3

hello I want to know how can I generically define function which can be apply to all of the UITextFields in specific UIViewController on which I am working in. Lets say If I have 10 textfields and I want all of them to be hidden, or seteditable false or true. I don't want to write like this textfield

textField1.hidden = true
textField2.hidden = true
textField3.hidden = true
etc etc

Hope you understand my question

hellosheikh
  • 2,929
  • 8
  • 49
  • 115
  • You can keep them in a `UIView' or `UIScrollView' then you just have to hide and show the `superview` of all textfields. Another way to create a `IBOutletCollection` . – Pawan Sharma Jan 28 '16 at 08:11
  • http://stackoverflow.com/questions/24052459/swift-iboutletcollection-equivalent – Pawan Sharma Jan 28 '16 at 08:13
  • I would subclass UIViewController and I would add a method setTextFieldsHidden:(bool)isHidden. Then inside the controller I would just iterate through the subView and check if it is a class of UITextField or not. – Teddy Jan 28 '16 at 08:15

4 Answers4

3
var hidden = true { didSet { view.subviews.forEach { ($0 as? UITextField)?.hidden = hidden } } }

This will hide / unhide all your textfields when you change the value of hidden

Eendje
  • 8,815
  • 1
  • 29
  • 31
1

You can recursively find all UITextField instances in your view with a function like this. Pass your highest level view that contains the UITextFields or the views that contain your UITextFields (since this is recursive) as the view parameter;

func getTextFieldsInView(view: UIView) -> [UITextField] {
    var arrayTextFields = [UITextField]()

    for subview in view.subviews {
        arrayTextFields += getTextFieldsInView(subview)

        if let subview = subview as? UITextField {
            arrayTextFields.append(subview)
            //you can also do what you want here like: subview.hidden = true
        }
    }
    return arrayTextFields
}

This way you don't have to add them one by one to an array. Just assign the function call to a variable and the array is created dynamically.

Batuhan C.
  • 384
  • 3
  • 10
0

You could keep an array of all textfields and then forEach through the collection.

let textFields = [textField1, textField2, textField3, textField4]
textFields.forEach { $0.hidden = true }
Christopher
  • 1,395
  • 2
  • 18
  • 32
0

If your text fields are in Interface Builder you could create an IBOutletCollection for them and perform operations on them as a group

// Swift
@IBOutlet var semiBoldLabels: [UITextField]!

// ObjC
@property (nonatomic, strong) IBOutletCollection(UITextField) NSArray *textFields;