Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all the textfields from a view in swift

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()
    }
}
like image 722
Kunal Kumar Avatar asked Dec 01 '16 10:12

Kunal Kumar


1 Answers

I made it working, but still need the explanation why the code in question is not working
I got it from somewhere on the forum, not exactle able to credit the answer.

/** extract all the textfield from view **/
func getTextfield(view: UIView) -> [UITextField] {
var results = [UITextField]()
for subview in view.subviews as [UIView] {
    if let textField = subview as? UITextField {
        results += [textField]
    } else {
        results += getTextfield(view: subview)
    }
}
return results  

Call the above function in viewDidLoad or viewDidLayoutSubviews.

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

/** setting bottom border to the textfield **/
    let allTextField = getTextfield(view: self.view)
    for txtField in allTextField
    {
        txtField.setBottomBorder()
    }
}
like image 97
Kunal Kumar Avatar answered Oct 24 '22 00:10

Kunal Kumar