ashForIos ashForIos - 4 months ago 38
iOS Question

Center align placeholder in textfield

I know this question been asked many times but as drawinrect deprecated and I need this in ios 8.As I have a textfield and I need the placeholder in center align and rest of the test left align.Please help me out.


Create and connect IBOutlet to your textField. In YourViewController.m

@interface YourViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *txt;

In your viewDidLoad


Write this delegate method..this method calls everytime when text in text field changes.

- (BOOL) textField: (UITextField *)theTextField shouldChangeCharactersInRange: (NSRange)range replacementString: (NSString *)string {

    NSRange textFieldRange = NSMakeRange(0, [self.txt.text length]);
    // Check If textField is empty. If empty align your text field to center, so that placeholder text will show center aligned
    if (NSEqualRanges(range, textFieldRange) && [string length] == 0) {
    else //else align textfield to left. 
    return YES;