jcr jcr - 9 months ago 112
iOS Question

Right align PlaceHolder text in UITextField

I have a UITextField with the text right-aligned.
I wanted to change the color of the placeholder text, so I use - (void)drawPlaceholderInRect:(CGRect)rect method. It works great BUT the placeholder text is left-aligned now (the text remains right-aligned). I guess I can add some code to override it but I didn't find which one. Thanks in advance !

- (void)drawPlaceholderInRect:(CGRect)rect
[[UIColor redColor] setFill];
UIFont *font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:18];
[[self placeholder] drawInRect:rect withFont:font];


You've discovered that "drawInRect" is automagically drawing from the left edge going right.

What you need to do is adjust the "rect" passed to "drawInRect" to have left edge that allows the right edge of the drawn text to touch the right edge of your UITextField rect.

To do this, I'd recommend using this method: NSString's [self placeholder] sizeWithFont: constrainedToSize:] (assuming [self placeholder] is a NSString) which will give you the true width of the string. Then subtract the width from the right edge of the text field box and you have the left edge where you need to start your drawing from.