0

I have found that I can set the placeholder color by changing the textColor of a label contained with UITextField.

[[UILabel appearanceWhenContainedIn:[UITextField class], nil] setTextColor:[UIColor lightGrayColor]];

But this also changes UITextField text color. Is there a way to specify them both separately from UIAppearance?

I tried to use the the setValue:forKey: but then I read that my app can be rejected for using KVC.

Lebyrt
  • 1,376
  • 1
  • 9
  • 18
Snymax
  • 357
  • 4
  • 18
  • 1
    Use the `attributedPlaceholder` property of `UITextField` instead. – rmaddy Apr 29 '14 at 19:08
  • this is wonderful but this must be set on each page correct in a function? i set it in the appDelegate but i am required to give a placeholder string which overrights my placeholders – Snymax Apr 29 '14 at 19:16
  • Yeah, looking at the way UITextField is built there does not appear to be a way to adjust the placeholder color via an appearance selector, meaning you will have to do it every time. Perhaps an easier alternative in your case is to just subclass UITextfield. Then you can perform your standard customizations by overriding the initializer and other appropriate methods. – Dima Apr 29 '14 at 19:18
  • @Snymax you could add a category on `UITextField` to set the `attributedPlaceholder` with a default color - `setDefaultStyledPlaceholder:` for example – Rich Apr 29 '14 at 19:18
  • Dima I think your a genius thank you i dont know why i didnt think of that – Snymax Apr 29 '14 at 19:20

1 Answers1

0

Building off @Synmax answer, I've put together this category you can use to add a placeholder text color to a UITextField:

@interface UITextField (Placeholder)

@property UIColor* placeholderTextColor;

@end

@implementation UITextField (Placeholder)

-(UIColor*)placeholderTextColor {
    return [self.attributedPlaceholder attribute:NSForegroundColorAttributeName atIndex:0 effectiveRange:nil];
}

-(void)setPlaceholderTextColor:(UIColor*)placeholderTextColor {
    if(self.attributedPlaceholder) {
        NSMutableAttributedString* as = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedPlaceholder];
        if(placeholderTextColor) {
            [as setAttributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName] range:NSMakeRange(0, self.attributedPlaceholder.length)];
        } else {
            [as removeAttribute:NSForegroundColorAttributeName range:NSMakeRange(0, self.attributedPlaceholder.length)];
        }
        self.attributedPlaceholder = as;
    } else if(self.placeholder) {
        self.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self.placeholder attributes:[NSDictionary dictionaryWithObject:placeholderTextColor forKey:NSForegroundColorAttributeName]];
    }
}

@end

You can then set the placeholder text color using appearance like this...

[UITextField appearance].placeholderTextColor = UIColor.grayColor;