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