fs_tigre fs_tigre - 2 months ago 12
iOS Question

Use UITextFieldDelegate for multiple fields

I have the following code to prevent the user from entering more than one period

.
in a
UITextField
, it works fine but I would like to do the same with other two textFields, how can this be done?

I tried assigning
delegate
to multiple fields and it doesn't quite work, it only works on the first to be comes the first responded.

class UserInputViewController: UIViewController, UITextFieldDelegate{
override func viewDidLoad() {
super.viewDidLoad()
self.myTextField.delegate = self
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1

if (periodsInTextField > 0 && string == "."){
return false
}
return true
}
}


EDIT(Answer) : Here is how it should be done based on @ KKRocks' answer below.

class UserInputViewController: UIViewController, UITextFieldDelegate{
override func viewDidLoad() {
super.viewDidLoad()
self.myTextField.delegate = self
self.secondTextField.delegate = self
self.thirdTextField.delegate = self
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1

if (periodsInTextField > 0 && string == "."){
return false
}
return true
}
}

Answer

Please change this line with

From :

let periodsInTextField = myTextField.text!.componentsSeparatedByString(".").count - 1

To :

let periodsInTextField = textField.text!.componentsSeparatedByString(".").count - 1