How to get all the textfields from a view in swift

前端 未结 8 849
予麋鹿
予麋鹿 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:41

    extension:

    extension UIView {
        func viewOfType<T:UIView>(type:T.Type, process: (_ view:T) -> Void)
        {        
            if let view = self as? T
            {
                process(view)
            }
            else {
                for subView in subviews
                {
                    subView.viewOfType(type:type, process:process)
                }
            }
        }
    }
    

    Usage:

    view.viewOfType(type:UITextField.self) {
            view in
    
            view.text = "123"
    }
    
    0 讨论(0)
  • 2020-12-17 18:44

    This worked for me.

    var textFieldsArray = [UITextField]()
    
    for view in self.view.subviews {
        if view is UITextField {
            textFieldsArray.append(view as! UITextField)
        }
    }
    
    textFieldsArray.forEach { $0.setBottomBorder() }
    

    If you want to get the result of the function applied in a new array, use map() instead.

    0 讨论(0)
提交回复
热议问题