How to get all the textfields from a view in swift

前端 未结 8 878
予麋鹿
予麋鹿 2020-12-17 17:53

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

8条回答
  •  余生分开走
    2020-12-17 18:20

    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()
        }
    }
    

提交回复
热议问题