Search code examples
iosobjective-ccocoa-touchuitextfieldsubclassing

How to use code from my UITextField subclass in other subclasses that have isEditing property


I've got subclass of UITextField which add some additional functionalities when field is editing. For UITextField all works correclty. Now what I want is to use this piece of code in other UIControl subclasses that have isEditing property and have field to add some text. Is it possible? Or maybe one correct way is to copy-paste this code to e.g. UITextView class?

Thank you in advance


Solution

  • Read this Stack Overflow answer, in particular Answerbot's response that details how to create a subclass of UITextField.

    If you want to use the code only in UITextField controls, then you have the option of subclassing UITextField as described by Answerbot, for example...

    subclassedTextField.h   (header file)
    #import <UIKit/UIKit.h>
    @interface subclassedTextField : UITextField
    @property (nonatomic, readwrite, assign) IBOutlet UITextField *fieldPrevious;
    @property (nonatomic, readwrite, assign) IBOutlet UITextField *fieldNext;
    @end
    
    subclassedTextField.m   (implementation file)
    #import subclassedTextField.h
    @implementation subclassedTextField
    @end
    

    (In this example the fieldNext & fieldPrevious properties enable "drag to associate" outlet connections from the Connection Inspector in Interface Builder, again as described by Answerbot.)

    Subclassing UIControl or creating a Category of UIControl as suggested by others will allow your code to be used by other UIControls, such as UITextView.

    The benefits of creating a Category - you do not have to import the subclassed UITextField (subclassedTextField in my example) into each class where you want to implement your code. Read the Apple documentation; the section titled "Categories Add Methods to Existing Classes".