5

So first, I needed to set the placeholder text color, so I subclassed the UITextfield as shown in several stack overflow posts. This works fine. Here is an example post of this: How do I subclass UITextField and override drawPlaceholderInRect to change Placeholder color.

But, when I try to use searchNameField.textAlignment = UITextAlignmentCenter; It is no longer centering the placeholder. The input text is still centered fine.

So then, assuming that the centering is not working because of the subclassing, what do I have to add to my UITextField subclass in order to have the placeholder text centered?

Thanks

Edit

Here is the code I used to solve this problem. This is placed inside my subclass of UITextField.

- (CGRect)placeholderRectForBounds:(CGRect)bounds 
{
    CGSize size = [[self placeholder] sizeWithFont:[UIFont fontWithName:@"Arial" size:placeholdTextSize]];

    return CGRectMake( (bounds.size.width - size.width)/2 , bounds.origin.y , bounds.size.width , bounds.size.height);
}

Note that placeholdTextSize is a property that I set during initialization.

Community
  • 1
  • 1
Jomnipotent17
  • 451
  • 7
  • 23

3 Answers3

5

Here you go buddy

subclassing UITextField will do the work:

// CustomTextField.h
@interface CustomTextField : UITextField {
}
@end

override the methods:

@implementation
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
    return CGRectMake(x,y,width,height);//Return your desired x,y position and width,height
}

- (void)drawPlaceholderInRect:(CGRect)rect {
    //draw place holder.
 [[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:12]];

}
@end
Rahul Vyas
  • 28,260
  • 49
  • 182
  • 256
  • 1
    Thank you. For completeness: to solve this problem, I used the 'placeholderRectForBounds' method. My edit in the original question shows the code for anyone that is interested. – Jomnipotent17 Jul 18 '12 at 11:31
4

i think this will work (tested)

- (void) drawPlaceholderInRect:(CGRect)rect {

      [[UIColor redColor] setFill];
      [self.placeholder drawInRect:rect
                          withFont:self.font
                     lineBreakMode:UILineBreakModeTailTruncation
                         alignment:self.textAlignment];
    }

https://github.com/mschulkind/cordova-true-native-ios/blob/master/Classes/UITextFieldPlugin.m

duchuy
  • 604
  • 5
  • 9
2

You can do this in UITextfield subclass

- (void)drawPlaceholderInRect:(CGRect)rect {

[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.8] setFill];

[[self placeholder] drawInRect:rect withFont:[UIFont boldSystemFontOfSize:16.0] lineBreakMode:UILineBreakModeTailTruncation alignment:NSTextAlignmentCenter];

}

vinod
  • 51
  • 5