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
anatoliy_v :
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:\n\nfunc textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {\n if textField == field1 {\n // do something\n } else if textField == field2 {\n // do something\n } else if textField == field3 {\n // do something\n }\n return true\n}\n\n\nDo not forget to make all field's delegate as self: field1.delegate = self etc.\n\nIn your case it will work fine. \n\nIf you want to know a better solution if you have much more fields (10, 20?) let me know and I'll update my answer.",
2015-06-03T21:21:20
dordio :
Best way to do this is using the tag attribute.\n\nAs seen on the Apple Docs:\n\n- (void)textFieldDidEndEditing:(UITextField *)textField {\n\n switch (textField.tag) {\n case NameFieldTag:\n // do something with this text field\n break;\n case EmailFieldTag:\n // do something with this text field\n break;\n // remainder of switch statement....\n }\n}\n\nenum {\n NameFieldTag = 0,\n EmailFieldTag,\n DOBFieldTag,\n SSNFieldTag\n};\n",
2018-12-28T18:08:31
Karol Zmysłowski :
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {\n switch textField {\n case field1:\n // do something \n case field2:\n // do something \n case field3:\n // do something \n }\n return true\n}\n",
2019-10-01T14:10:37