Harish
Harish

Reputation: 2512

iPhone UITextField - Change placeholder Font and Text Color

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.

Upvotes: 2

Views: 8740

Answers (3)

Stan
Stan

Reputation: 1573

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
}

Upvotes: 0

Fahim Parkar
Fahim Parkar

Reputation: 31627

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...";

Upvotes: 2

kraftydevil
kraftydevil

Reputation: 5246

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];

Upvotes: 6

Related Questions