Thursday 15 May 2014

UITextField with placeholder color. iOS6 using attributed text property (also in xib file) and iOS5 using drawRect:


For ios 6:
Use attributedPlaceholder property

Method 1: Without Subclassing

UIColor *color = [UIColor blackColor];
textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:placeholderText attributes:@{NSForegroundColorAttributeName: color}];

Method 2: Creating category

//--------------------.h file---------------------
//  UITextField+URLEncoding.h
//

#import <Foundation/Foundation.h>

@interface UITextField (Extension)

-(void)setPlaceholder:(NSString *)placeholderText WithColor:(UIColor*)color;


@end



//--------------------.m file---------------------
//  UITextField+URLEncoding.m
//

#import "UITextField+Extension.h"

@implementation UITextField (Extended)

-(void)setPlaceholder:(NSString *)placeholderText WithColor:(UIColor*)color;
{
    if ([self respondsToSelector:@selector(setAttributedPlaceholder:)]) {
        UIColor *color = [UIColor blackColor];
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString: placeholderText attributes:@{NSForegroundColorAttributeName: color}];
    } else {
        NSLog(@"Cannot set placeholder text's color, because deployment target is earlier than iOS 6.0");
        // set default placeholder color.
        self.placeholder = placeholderText;
    }
}

@end

Method 3

Using xib property. In Interface Builder, select file inspector and add new key value pair to update the placeholder color
Key: "_placeholderLabel.textColor"
Type: Color
Value: Create/select color to be used.






For iOS 5:

You can override drawPlaceholderInRect:(CGRect)rect the placeholder text 
- (void) drawPlaceholderInRect:(CGRect)rect {
    [[UIColor grayColor] setFill];
    [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:14]];
}

Courtesy Stack Overflow