Monday 9 September 2013

Need to center placeholder text in custom UITextField vertically in iOS

Need to center placeholder text in custom UITextField vertically in iOS

I am working on an iOS application where I have subclassed my UITextField
in order to set the colour of my placeholder text. I have also centered it
horizontally, but my problem is that my placeholder text is not centered
vertically, and for some reason, the cursor is not centered within the
placeholder text, but instead appears just after the very first character
of the placeholder text.
My method in my subclass of UITextField which I override in order to set
the colour of the placeholder text and center the text horizontally looks
like this:
- (void)drawPlaceholderInRect:(CGRect)rect {
// Set colour and font size of placeholder text
[[UIColor whiteColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont
systemFontOfSize:28] lineBreakMode:UILineBreakModeMiddleTruncation
alignment:NSTextAlignmentCenter];
}
Here is my code where I create and set up my UITextField:
_field = [[CustomTextField alloc] initWithFrame:CGRectMake(190, 300, 644,
64)];
_field.delegate = (id)self;
[_field becomeFirstResponder];
[_field setBackgroundColor:[UIColor darkGrayColor]];
[_field setTextColor:[UIColor whiteColor]];
[_field setPlaceholder:@"Enter First and Last Name"];
[[_field layer] setMasksToBounds:8.0f];
[[_field layer] setBorderColor:[[UIColor grayColor] CGColor]];
[[_field layer] setBorderWidth:1.0f];
[_field setFont:[UIFont fontWithName:@"Arial" size:25]];
[_field setReturnKeyType:UIReturnKeyDone];
[_field setTextAlignment:NSTextAlignmentCenter];
_field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
[self.view addSubview:_field];
I initially subclassed my UITextField because while everything looked
fine, my placeholder text for some reason was grey instead of white (which
I set as the text colour for the textfield). Ironically, the placeholder
text was centered both vertically AND horizontally, AND the cursor was
centered. So in order to correct the placeholder text colour, I subclass
the UITextField, only to open up more problems now. Sheesh.
Is there a way that I can now center the placeholder text vertically, as
well as have the cursor centered as well? Better still, is there a way for
me to change the grey colour of the placeholder text to white without
having to subclass it? This would be ideal.
Thanks in advance to all who reply.

No comments:

Post a Comment