0

I have this subclass of UITextField and I would like to set a property as background color, border etc of UITextField. I don't know, if I use right method, because when I use this class for a UItextField, the UITextField doesn't change.. In which method I have to declare this properties?

#import "defaultUITextField.h"

@implementation defaultUITextField

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.delegate = self;
        [self setBackgroundColor:([UIColor redColor])];

        UIColor *borderColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:233.0/255.0];

        self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
        self.leftViewMode = UITextFieldViewModeAlways;

        self.layer.borderColor = [borderColor CGColor];
        self.layer.borderWidth = 1.0f;
    }
    return self;
}

@end
Cœur
  • 37,241
  • 25
  • 195
  • 267
krata
  • 101
  • 10

1 Answers1

2

your solution seems to be right. how did you place your suctom TextField on a View? If you created your TextField in Interface Builder then you overrided the wrong constructor.

- (id)initWithCoder:(NSCoder *)inCoder {
    if (self = [super initWithCoder:inCoder]) {
        self.delegate = self;
        [self setBackgroundColor:([UIColor redColor])];

        UIColor *borderColor = [UIColor colorWithRed:233.0/255.0 green:233.0/255.0 blue:233.0/255.0 alpha:233.0/255.0];

        self.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 20)];
        self.leftViewMode = UITextFieldViewModeAlways;

        self.layer.borderColor = [borderColor CGColor];
        self.layer.borderWidth = 1.0f;
    }
    return self;
}

this constructor is called when you create UITextField in IB and change its class to UItextField.

user3485986
  • 176
  • 1
  • 3
  • 15
  • I have the UITexfield on Storyboard and it is connection with View with IBOutlet the IBOutlet has a class of defaultUITextField, but it doesn't work. Your method work only when I set a class at storyboard. I don't know if it's clearly. But I have to use method initWithCoder and set defaultUITextField class at storyBoard. It is little bit strange. Why it doesn't work only after this declaration at view: @property (strong, nonatomic) IBOutlet defaultUITextField *classNameTextField; – krata Apr 19 '14 at 08:42
  • In order for a control to be of a custom class you need to set the class directly in storyboard, because storyboard is responsible for creating the instance of that control. If you have UITextField * tf = [[UITextField alloc]init]; tf - instance of class UITextField. defaultTExtField * dtf = tf; now dtf and tf is the same object of class UITextField. saving pointer to another variable doesn't change it's class. AS the matter of fact, it's not possible to change the class of an object after it has been created. – user3485986 Apr 19 '14 at 09:06