Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS swift delegate with more than 1 uitextfield in a uiview

I have an iOS app, with one UIView and three UITextField (more than 1) I would to understand what are the best practices for my class ViewController to manage the UITextField.

- class MainViewController: UIViewController, UITextFieldDelegate ?

I wonder that, because I have more than one UITextField and only one func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool

like image 829
FREDERIC1405 Avatar asked Jun 03 '15 20:06

FREDERIC1405


1 Answers

Easiest way is to know what text field to use in delegate methods. I.e. you have 3 text fields: field1, field2, field3 and when delegate called you can detect what to do:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField == field1 {
        // do something
    } else if textField == field2 {
        // do something
    } else if textField == field3 {
        // do something
    }
  return true
}

Do not forget to make all field's delegate as self: field1.delegate = self etc.

In your case it will work fine.

If you want to know a better solution if you have much more fields (10, 20?) let me know and I'll update my answer.

like image 142
anatoliy_v Avatar answered Oct 01 '22 05:10

anatoliy_v