2

I have a UITextField where i need to change the Placeholder Font and Color, i'm calling the below method in drawRect method,

-(void) setFontColorForPlaceHolder
{
    for(id obj in [[self baseScrollView] subviews])
    {
        if([obj isKindOfClass:[UITextField class]])
        {
            [obj setAttributedPlaceholder:[[NSAttributedString alloc]initWithString:[obj placeholder] attributes:@{
                NSFontAttributeName:kFutura_Medium_14 ,NSForegroundColorAttributeName:[UIColor redColor]
            }]];
        }
    }
}

Here the COLOR is changing but the FONT is not setting. What is the issue here with setAttributedPlaceholder.

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Harish
  • 2,496
  • 4
  • 24
  • 48
  • 1
    There are lots of links available for this try this one http://stackoverflow.com/questions/18244790/changing-uitextfield-placeholder-font – Agent Chocks. Apr 26 '14 at 11:47
  • 1
    setAttributedPlaceholder Not Working in ios6 – Mitul Bhadeshiya Apr 26 '14 at 12:35
  • @MitsBhadeshiya : Yes absolutely you are right, its working fine in iOS7. So what to do in iOS6.? – Harish Apr 26 '14 at 13:03
  • 1
    Why are you calling this code from `drawRect:`? That's not appropriate at all. – rmaddy Apr 26 '14 at 15:38
  • @rmaddy So where can i call it?? – Harish Apr 26 '14 at 16:52
  • 1
    Setting the placeholder of a `UITextField` subview isn't part of drawing a custom view. You should set the placeholder once when creating the custom view such as in its `init...` method. A custom view's `drawRect:` should only be used to draw the custom content (if any) of the view. If your custom view only has subview and no custom drawing, you shouldn't even implement the `drawRect:` method. – rmaddy Apr 26 '14 at 16:55

3 Answers3

6

I was testing in iOS 7.1 and found out that NSFontAttributeName isn't doing anything to UITextField's placeholder text.

However, when I changed the font of the UITextField itself, the placeholder text font changed as well:

aUITextField.font = [UIFont fontWithName:@"HelveticaNeue-Thin" size:20.0f];
kraftydevil
  • 5,144
  • 6
  • 43
  • 65
2

For iOS 6+

[textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];

To set a font for placeholder, just set a font for textfield before writing textholder.

textField.font = your font here;
[textField setValue:your_color forKeyPath:@"_placeholderLabel.textColor"];
textField.placeholder = "your placeholder string here...";
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
0

SWIFT 3 In your custom class override this:

override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
     //set initial attributed placeholder color and font
     self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSForegroundColorAttributeName: placeholderColor, NSFontAttributeName: placeholderTextFont])
     return bounds
}
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Stan
  • 1,513
  • 20
  • 27