skip to Main Content

I’ve created a text field editing func to reset corner radius and border color. I’ve seven text fields in my project. Now I want to call this function for all text fields with short code.

This is how I’ve written my code:

textField1.editFunc()
textField2.editFunc()
textField3.editFunc()
textField4.editFunc()
textField5.editFunc()
textField6.editFunc()
textField7.editFunc()

2

Answers


  1. You can try

    [textField1, textField2, textField3, 
     textField4, textField5,textField6,textField7].forEach { $0.editFunc() }
    

    OR

    view.subviews.forEach {
      ($0 as? UITextField)?.editFunc()
    }
    

    OR

    Create outlet collection and link all textfields to it

     @IBOutlet weak var allF:[UITextField]!
    

    Then

    allF.forEach { $0.editFunc() }
    
    Login or Signup to reply.
  2. Use a custom textfield class to customise:

    class RoundedUITextField: UITextField {
        
        override init(frame: CGRect) {
            super.init(frame: frame)
        }
        
        required init?(coder aDecoder: NSCoder) {
            super.init(coder: aDecoder)
        }
        
        override func awakeFromNib() {
            super.awakeFromNib()
            self.editFunc()
        }
        
        func editFunc() {
            //Code here
        }
    }
    

    Usage:

    @IBOutlet weak var textField1: CustomTextField!
    @IBOutlet weak var textField2: CustomTextField!
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search