Reputation: 55
I would like to have a variable that tells me which Textfield was just edited. Therefor the variable needs to has the Type UITextField. But how can i initialize it?
var whichTextFieldWasEditited = UITextField
init() { }
Upvotes: 0
Views: 856
Reputation: 331
All UITextFields have protocol that you can conform to. https://developer.apple.com/documentation/uikit/uitextfielddelegate
The protocol has 6 different methods, the one you're looking for is textFieldDidEndEditing
The easiest way to differentiate between UITextFields is to assign them tags. All UIViews (and subclasses) have a tag such that they can be identified.
To be able to use this protocol method to your advantage you need to set the UITextField's delegate to "self" which in your case will be the view controller, as well as set the tags for the UITextFields
To tie it all in together
class MyViewController: UIViewController, UITextFieldDelegate {
let textField1 = UITextField() //() is the constructor for the object
let textField2 = UITextField()
init(){ //some generic init
super.init()
textField1.delegate = self
textField1.tag = 1
textField2.delegate = self
textField2.tag = 2
}
//protocol method
func textFieldDidEndEditing(_ sender: UITextField){
//since the sender is of UITextField
if sender.tag == 1 { //it's textField1
//do something
}
if sender.tag == 2 { //it's textField2
//do something
}
}
}
Note: This is just a skeleton example, the important take aways is that your class needs to conform to the UITextFieldDelegate, you need to assign your text field's delegates to yourself, you need to set their tags and then you can differentiate between them in the protocol methods.
Upvotes: 2