Home > Software design >  How can I call one same function for multiple textfields in swift?
How can I call one same function for multiple textfields in swift?

Time:03-02

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

CodePudding user response:

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!

CodePudding user response:

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