I have subclass the UITextField class and did the below code
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:NSTextAlignmentLeft];
}
I have also written
self.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
line of code
This placeholder text is properly center aligned in ios6 but not in ios7 it is showing top aligned.
Although text I type is appearing centered.It only has issue with placeholder string.
I have tried with xib to set placeholder string.In XIB it is showing properly but when I run the code textfield placeholder is top aligned.
Any workaround for this?
Vadoff's answer worked for me. Still this is the full implementation that might help anyone with the same issue.
drawInRect
method is deprecated in ios7 and drawInRectWithAttributes
works
- (void)drawPlaceholderInRect:(CGRect)rect
{
[self.placeHolderTextColor setFill];
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.placeHolderFont.pointSize)/2 - 2, rect.size.width, self.placeHolderFont.pointSize);
rect = placeholderRect;
if(iOS7) {
NSMutableParagraphStyle* style = [[NSMutableParagraphStyle alloc] init];
style.lineBreakMode = NSLineBreakByTruncatingTail;
style.alignment = self.placeHolderTextAlignment;
NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:style,NSParagraphStyleAttributeName, self.placeHolderFont, NSFontAttributeName, self.placeHolderTextColor, NSForegroundColorAttributeName, nil];
[self.placeholder drawInRect:rect withAttributes:attr];
}
else {
[self.placeholder drawInRect:rect
withFont:self.placeHolderFont
lineBreakMode:NSLineBreakByTruncatingTail
alignment:self.placeHolderTextAlignment];
}
}
drawInRect methods seem to behave differently in iOS7, you can try adding the following line and use that as the rect to draw instead. It's also backwards compatible with pre-iOS7.
CGRect placeholderRect = CGRectMake(rect.origin.x, (rect.size.height- self.font.pointSize)/2, rect.size.width, self.font.pointSize);
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