corroded
corroded

Reputation: 21564

How do you make a subclass of UITextField?

I am planning to subclass UITextField so I can customise the look and feel of textfields in my app globally. Based on the design in our mockups, textfields should have a green border which I already did for one of my textfields. (source: https://stackoverflow.com/a/5749376/334545)

I also changed placeholder color as said here: https://stackoverflow.com/a/19852763/334545

But all these are for just one textfield. I want all of my other textfields to have this so I tried subclassing by creating a new uitextfield class which I tried using. I added the methods above to MYUITextField.m's initWithFrame method:

- (id)initWithFrame:(CGRect)frame
{
   self = [super initWithFrame:frame];
   if (self) {
       // Initialization code
       UIColor *greenColor = [UIColor colorWithRed:122.0/255.0 green:168.0/255.0 blue:73.0/255.0 alpha:1.0];
       UIColor *greyColor = [UIColor colorWithRed:87.0/255.0 green:87.0/255.0 blue:87.0/255.0 alpha:1.0];

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

       self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"" attributes:@{NSForegroundColorAttributeName: greyColor}];

   }
   return self;
}

Should I just change the drawRect method? Will the app be slower because of it?

Upvotes: 0

Views: 762

Answers (2)

AdamPro13
AdamPro13

Reputation: 7400

I believe the way you are doing it will be more efficient. -drawRect: can be called multiple times. By setting the values in -initWithFrame: you only ensure these only get set once.

That being said I am pretty sure the performance difference will be negligible.

EDIT: This is if you're doing things programmatically. If using nibs or storyboards, use the method -awakeFromNib.

Upvotes: 1

SwiftArchitect
SwiftArchitect

Reputation: 48514

When using NIB, you need to tell the resource about your custom class.

Set the Custom Class to MYUITextField like so:

  1. Select your TextField
  2. Xcode > View > Utilities > Show Identity Inspector
  3. In the Custom Class dropdown, pick your custom class

If using a resource, override -awakeFromNib instead of -initWithFrame::

-(void)awakeFromNib
{
    [super awakeFromNib];
    self.layer.borderColor=[[UIColor greenColor] CGColor];
    self.layer.borderWidth= 1.0f;
    self.attributedPlaceholder = [[NSAttributedString alloc]
                                  initWithString:@""
                                      attributes:@{NSForegroundColorAttributeName:
                                                   [UIColor greyColor]}];
}

See init and awakeFromNib for more details.

Upvotes: 2

Related Questions