Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField placeholder string is always Top aligned in ios7

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

}
like image 990
Heena Avatar asked Sep 30 '13 11:09

Heena


1 Answers

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);
like image 174
Vadoff Avatar answered Oct 09 '22 13:10

Vadoff