betweentwoworlds
betweentwoworlds

Reputation: 31

How do I centre UITextField cursor after user input consistently

I have a UITextField that I want to centre all content (text, cursor) at all times. Is this possible in iOS 7? My current initialisation of the view is shown below.

self.textField = [[UITextField alloc] init];
self.textField.delegate = self;
[self.textField setTextAlignment:NSTextAlignmentCenter];
self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
self.textField.placeholder = NSLocalizedString(@"Enter some text", @"The placeholder text to use for this input field");

My requirement for this is that when I click in the UITextField, the placeholder text should disappear, and show the cursor in the middle of the UITextField.

Currently, this seems to be intermittently positioned either in the middle of the text field or on the left of the text field irrelevant of where I click. Anybody got any suggestions as to how I can solve this or is it a known issue in iOS?

Upvotes: 2

Views: 3252

Answers (1)

Ty Lertwichaiworawit
Ty Lertwichaiworawit

Reputation: 2950

If you're creating you UITextField in you Storyboard you should not initialise and alloc it in code.

You need to use you Textfield delegates to accomplish this..

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.textField.delegate = self;
    [self.textField setTextAlignment:NSTextAlignmentCenter];
    self.textField.contentVerticalAlignment = UIControlContentVerticalAlignmentTop;
    [self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
    self.textField.placeholder = @"Enter some text";
}

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    //this removes your placeholder when textField get tapped
    self.textField.placeholder = nil;
    //this sets your cursor to the middle
    self.textField.text = @" ";
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    self.textField.placeholder = @"The placeholder text to use for this input field";
}

This surely does the trick.. Please accept the answer if it helps.

UPDATE

With code below when user press backspace the cursor will not align the text to the left.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:string];
    NSLog(@"propose: %@", proposedNewString);

    if ([proposedNewString isEqualToString:@""])
    {
        textField.text = [@" " stringByAppendingString:textField.text];
    }

    return YES;
}

Upvotes: 3

Related Questions