Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

becomeFirstResponder not working in iOS 8

I am using UITextField's method becomeFirstResponder to show the keyboard. This is working in iOS 7. But in iOS 8 this method doesn't show the keyboard.

 UITextField *txtAddNew = [[UITextField alloc] initWithFrame:CGRectMake(10,10,240, 21)];
 txtAddNew.font = [UIFont fontWithName:@"Helvetica" size:16];
 txtAddNew.clearButtonMode = UITextFieldViewModeWhileEditing;
 txtAddNew.returnKeyType = UIReturnKeyDone;
 txtAddNew.delegate = self;
 txtAddNew.autocorrectionType = UITextAutocorrectionTypeNo;
 txtAddNew.tag = 15;

 // Open keyboard
 [txtAddNew becomeFirstResponder];

Is there any way to do it in iOS 8?

like image 627
Tejas Bharambe Avatar asked Nov 24 '14 04:11

Tejas Bharambe


3 Answers

Try calling becomeFirstResponder like below

[txtAddNew performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0];

As per Apple,

A responder object only becomes the first responder if the current responder can resign first-responder status (canResignFirstResponder) and the new responder can become first responder.

You may call this method to make a responder object such as a view the first responder. However, you should only call it on that view if it is part of a view hierarchy. If the view’s window property holds a UIWindow object, it has been installed in a view hierarchy; if it returns nil, the view is detached from any hierarchy.

like image 197
thavasidurai Avatar answered Oct 16 '22 11:10

thavasidurai


Swift 3

Here is the swift 3 version of the accepted answer. For me to get it to work I also had to add a delay.

txtAddNew.perform(
    #selector(becomeFirstResponder), 
    with: nil, 
    afterDelay: 0.1
)
like image 17
Jacob Arvidsson Avatar answered Oct 16 '22 12:10

Jacob Arvidsson


I think you missed the addsubview the txtAddNew to the Mainview

   txtAddNew.tag = 15;
   [self.view addsubview:txtAddNew];  

   // Open keyboard
  [txtAddNew becomeFirstResponder];
like image 3
Anbu.Karthik Avatar answered Oct 16 '22 12:10

Anbu.Karthik