How to get all the textfields from a view in swift

Kunal Kumar picture Kunal Kumar · Dec 1, 2016 · Viewed 7k times · Source

I have a view which has more than 15 UITextFields. I have to set bottomBorder(extension) for all the UITextFields. I can set it one by one for all the UITextFields and its working too. I want to set the bottom border for all the UITextFields at once. Here is the code I am trying but it seems like that for loop is not executing. I have even tried it in viewDidLayoutSubViews but for loop not executing there too.

 override func viewDidLoad() 
{
    super.viewDidLoad()

    /** setting bottom border of textfield**/

    for case let textField as UITextField in self.view.subviews {
        textField.setBottomBorder()
    }
}

Answer

Gurjit Singh picture Gurjit Singh · Jan 10, 2018

Swift: This function will return all text-fields in a view. No matter if field exists in any subview. ;-)

func getAllTextFields(fromView view: UIView)-> [UITextField] {
    return view.subviews.flatMap { (view) -> [UITextField]? in
        if view is UITextField {
            return [(view as! UITextField)]
        } else {
            return getAllTextFields(fromView: view)
        }
    }.flatMap({$0})
}

Usage:

_=getAllTextFields(fromView : self.view).map{($0.text = "Hey dude!")}