Search code examples
iosuitextfieldplaceholder

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.


Solution

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

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

    In your viewDidLoad

    self.txt.delegate=self;
    self.txt.textAlignment=NSTextAlignmentCenter;
    

    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) {
        self.txt.textAlignment=NSTextAlignmentCenter;
        }
        else //else align textfield to left. 
        {
            self.txt.textAlignment=NSTextAlignmentLeft;
        }
        return YES;
    }