Changing UITextField Placeholder font

Bob Yousuk picture Bob Yousuk · Aug 15, 2013 · Viewed 66.2k times · Source

I'm changing the placeholder text color with the following code, but when I try to add NSFontAttribute I get the compiler error "too many arguments to method call, expect 2 have 3"

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color},@{NSFontAttributeName:@"Roboto-Bold"}]; 

This Works Fine:

 UIColor *color = [UIColor blackColor];
        _nameField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Your Name" attributes:@{NSForegroundColorAttributeName: color}]; 

Answer

ddevaz picture ddevaz · Aug 15, 2013

Objective-C:

UIColor *color = [UIColor blackColor];    
someUITextField.attributedPlaceholder =
  [[NSAttributedString alloc] initWithString:@"Placeholder Text"
    attributes:@{
       NSForegroundColorAttributeName: color,
       NSFontAttributeName : [UIFont fontWithName:@"Roboto-Bold" size:17.0]
    }
  ];

(There are no brackets between literal dictionary key-value pairs.)

Swift:

let attributes = [
    NSForegroundColorAttributeName: UIColor.blackColor(),
    NSFontAttributeName : UIFont(name: "Roboto-Bold", size: 17)! // Note the !
]

someUITextField.attributedPlaceholder = NSAttributedString(string: "Placeholder Text", attributes:attributes)