Isaac A
Isaac A

Reputation: 387

How to programmatically deselect UITextField

I have a UITextField which I can click on, and edit the contents of. I am running code when the UITextField is pressed by using:

[personalCountryLabel addTarget:self action:@selector(countryPressed) forControlEvents:UIControlEventEditingDidBegin];  

This presents another view controller. However, when I click the back button, the UITextField is still selected, so the text runs again, sending me back to the view controller.

I use the code:

textField.enabled = false;

and

textField.enabled = true;

to respectively turn off and on the editing of the UITextField, but doing this in succession does not unselect the UITextField.

How can I therefore programmatically deselect the UITextField (i.e, where the line cursor is no longer blinking).

Upvotes: 1

Views: 2474

Answers (3)

Kiran Bhoraniya
Kiran Bhoraniya

Reputation: 103

/* Programmatically deselect the Uitextfiels below this Code */

UITextField *txtDeselect = [[UITextField alloc]initWithFrame:CGRectMake(self.view.frame.origin.x+20, self.view.frame.origin.y+20, self.view.frame.size.width-40, 40)];
    [txtDeselect setBackgroundColor:[UIColor yellowColor]];
    [txtDeselect setBorderStyle:UITextBorderStyleRoundedRect];
    [txtDeselect setTextAlignment:NSTextAlignmentCenter];
    [txtDeselect setText:@"Email"];
    txtDeselect.enabled = NO;
    [self.view addSubview:txtDeselect];

Upvotes: 1

MoLowKey
MoLowKey

Reputation: 1144

did you set outlet & delegate of UITextField in your view controller ? why you use UItextfield for this ?

i recommend you use one of this before presenting new view controller :

option 1 :

[youtextfield resignFirstResponder];

//please sure you outlet connected & ....

you can call this on your viewWillAppear

option 2 :

[self.view endEditing:YES]; // this regularly
happend after present another VC)

you shouldn't use shouldEndEditing

Upvotes: 0

brandonscript
brandonscript

Reputation: 73034

If I understand what you're asking correctly, you just want:

[textField resignFirstResponder];

Upvotes: 5

Related Questions