Vertically centering a UITextField's attributedPlaceholder
ios, iphone, objective-c
Solution
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 :)
Problem
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?