Centering placeholder text in a subclass of UITextField

So, first I needed to set the color of the placeholder text, so I subclassed the UIText field, as shown in several columns. It works great. Here is an example of this: How to subclass UITextField and override drawPlaceholderInRect to change the color of bookmarks .

But when I try to use searchNameField.textAlignment = UITextAlignmentCenter;, it no longer centers the placeholder. The input text is still in the center.

So, assuming that centering is not working due to the subclass, what do I need to add to my subclass of UITextField in order to have dot text centered?

thank

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

, placeholdTextSize - , .

+5
3

UITextField :

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

:

@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
+5

, ()

- (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

+3

You can do this in a subclass of UITextfield

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

}

+2
source

All Articles