Search code examples
iosuitextfielddelegate

textFieldShouldReturn and shouldChangeCharactersInRange


Is it possible to have textFieldShouldReturn and shouldChangeCharactersInRange in two different locations.

Currently I am using shouldChangeCharactersInRange in a separate file as many of my files uses it - it function as only numbers will appear in textfield.

However I want each individual files to have their own unique textFieldShouldReturn as the textfield id is unique. Any suggested way to do this as I know each textfield can only hold one delegate?


Solution

  • Since both methods are from the same protocol you must have both in the same file. However, the implementation of shouldChangeCharactersInRange: can be written to call some common method that does the actual work.

    Something like, for example:

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        return [someHelper textField:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    

    where someHelper is the class implementing the shared implementation.