I am currently unable to vertically align an attributedPlaceholder inside a UITextField and I've no idea why.
Here's what I am doing:
self.addressBar = [[UITextField alloc] initWithFrame: CGRectMake(...)];
self.addressBar.backgroundColor = [UIColor whiteColor];
self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder text"
attributes:@{
NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f],
NSFontAttributeName : [UIFont fontWithName:@"Gotham-BookItalic" size:14.0],
}
];
self.addressBar.delegate = self;
self.addressBar.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:self.addressBar];
And here's what happening:
It's quite clear that this happens due to the fact that the UITextFieldLabel's height is 10px smaller than the UItextField itself, but I can't seem change that.
This only happens using an attributedPlaceholder though; the default placeholder property works just fine.
Any ideas?
Use NSParagraphStyle
to increase minimum line height:
NSMutableParagraphStyle *style = [self.addressBar.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
style.minimumLineHeight = self.addressBar.font.lineHeight - (self.addressBar.font.lineHeight - [UIFont fontWithName:@"Gotham-BookItalic" size:14.0].lineHeight) / 2.0;
self.addressBar.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder text"
attributes:@{
NSForegroundColorAttributeName: [UIColor colorWithRed:79/255.0f green:79/255.0f blue:79/255.0f alpha:0.5f],
NSFontAttributeName : [UIFont fontWithName:@"Gotham-BookItalic" size:14.0],
NSParagraphStyleAttributeName : style
}
];
You could also override a - (CGRect)placeholderRectForBounds:(CGRect)bounds;
method in UITextField
subclass.
It's messy, but it works :)
Placeholder will not be aligned if your textfield's text font is different than that of textfield's placeholder's font. Make sure both the font are same if you want to align properly or else you can follow kean's answer.
textField.font = [UIFont fontWithName:@"HelveticaNeue" size:12];
textField.attributedPlaceholder =
[[NSAttributedString alloc] initWithString:@"Enter fruit/vegetable name"
attributes:@{
NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue" size:12.0]
}
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With