Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color

I have a 3 UITextField with placeholder text set. On one of the UITextField I want the placeholder text to be red.

Now after googling it seems the best way to do this is to subclass UITextField and override drawPlaceholderInRect.

How do I go about subclassing and overriding drawPlaceholderInRect? I've not found any code examples or tutorials on this and I'm new to objective-c and iOS development so finding it tricky to work it out.

Answer:

Created a new objective-c class called CustomUITextFieldPlaceholder which subclassed UITextField. In CustomUITextFieldPlaceholder.m put the following code

 @implementation CustomUITextFieldPlaceholder

- (void)drawPlaceholderInRect:(CGRect)rect {
    // Set colour and font size of placeholder text
    [[UIColor redColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];
}

@end

To implement the above in your project

#import "CustomUITextFieldPlaceholder.h"

and

IBOutlet CustomUITextFieldPlaceHolder *txtName;

Note: This works and I believe is correct practice, however I have not fully tested it. Hope this example helps others in my situation.

Edit:

Changed

[[UIColor redColor] setFill];

for

[[UIColor colorWithRed:255.0 green:0.0 blue:0.0 alpha:0.7] setFill];

So that I could set the opacity to 70% to mimic default placeholder.

like image 238
Matt Price Avatar asked May 27 '11 11:05

Matt Price


People also ask

How do I change the placeholder color in UITextField in IOS Swift?

Create UITextField Extension like this: extension UITextField{ @IBInspectable var placeHolderColor: UIColor? { get { return self. placeHolderColor } set { self. attributedPlaceholder = NSAttributedString(string:self.

How do you change the placeholder color on a storyboard?

The easiest method to modify the placeholder text color is through the Xcode storyboard interface builder. Select the UITextField of interest and open the identity inspector on the right. Click on the plus symbol in the User Defined Runtime Attributes and add a new row with Key Path as placeholderLabel.


1 Answers

To answer you specific question, this is how subclassing works:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end

Here's how to override the method:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);
}
@end

However I don't think that's the method you want to override. I think this is what you're looking for:

@implementation
- (void)drawPlaceholderInRect:(CGRect)rect {
    // Your drawing code.
}
@end
like image 124
Erik B Avatar answered Sep 20 '22 12:09

Erik B