Overriding the drawPlaceholderInRect:
method to draw our own placeholder text.
- (void)drawPlaceholderInRect:(CGRect)rect
{
UIColor *colour = [UIColor darkColor];
if ([self.placeholder respondsToSelector:@selector(drawInRect:withAttributes:)]) {
// iOS7 and later
NSDictionary *attributes = @{NSForegroundColorAttributeName: colour, NSFontAttributeName: self.font};
CGRect boundingRect = [self.placeholder boundingRectWithSize:rect.size options:0 attributes:attributes context:nil];
[self.placeholder drawAtPoint:CGPointMake(0, (rect.size.height/2)-boundingRect.size.height/2) withAttributes:attributes];
}
else {
// iOS 6
[colour setFill];
[self.placeholder drawInRect:rect withFont:self.font lineBreakMode:NSLineBreakByTruncatingTail alignment:self.textAlignment];
}
}
OR
This case, likely crash if the internal variable changes in the future
Programmatically:
[self.MyTextField setValue:[UIColor blackColor] forKeyPath:@"_placeholderLabel.textColor"];
In UIStoryBoard
:
OR
EDIT:
Playing with UITextFiled delegates. its like a tricky:
-(void)viewDidLoad{
self.mytxtField.text = @"PlaceholderText";
self.mytxtField.delegate = self;
self.mytxtField.textColor = [UIColor darkGrayColor];
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
if ([self.mytxtField.text isEqualToString: @"PlaceholderText"]) {
self.mytxtField.text = @"";
self.mytxtField.textColor = [UIColor blackColor];
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField{
if ([self.mytxtField.text length]<1) {
self.mytxtField.text =@"PlaceholderText";
self.mytxtField.textColor = [UIColor darkGrayColor];
}
placeholder
property after this. Also make suretextField
isn'tnil
when you call the code. – Flak