问题
really simple question:
I got a view that consists of two textfields. When the view loads I want the keyboard to automatically pop up and focus the first field.
How do I do that? (In code? In IB?)
Thanks a lot! wasabi
回答1:
In your viewDidAppear: method call [yourTextField becomeFirstResponder].
回答2:
[myTextField becomeFirstResponder] should do the trick.
Also make sure you implement the UITextFieldDelegate methods where you can hide the first responder.
回答3:
Well, i know this question has already been answered many times. It takes time to display a keyboard after viewDidAppear method gets called.
The reason that viewDidAppear is the last method which gets called in view life cycle after it disappears of course. Also, keyboard needs to be created as well, if it couldn't be found in memory. So, the first time it takes more time as i expected. These reasons cause a little delay that was bugging me.
I always call becomeFirstResponder method in viewWillAppear method to decrease displaying time for the keyboard, but i needed to display keyboard just after viewDidAppear method to not lose smooth animation.
So, this little trick i came up with works like a charm. I tested it both on simulator and devices. If it doesn't work properly in your case, you have no other option but make it work as explained in accepted answer.
Well, what i'm doing is to create a UITextField (you can use any view that interacts with keyboard) and call become and resign first responder methods to put my keyboard in memory, if it isn't created yet. So, the second time, you're going to get keyboard in cache which accelerate keyboard displaying time. Well, i put these code the previous view controller that i'm going to display keyboard after.
Here is the code :
- (void)viewDidAppear:(BOOL)animated
{
UITextField *textField = [[UITextField alloc]init];
[self.view addSubview:textField];
[textField becomeFirstResponder];
[textField resignFirstResponder];
[textField removeFromSuperview];
}
回答4:
As a clarification to MarkGranoff's answer;
If you put the [yourTextField becomeFirstResponder] inside viewDidLoad or viewWillAppear - it will show the keyboard without waiting for a second or two (which happens if you put the becomeFirstResponder call inside the viewDidAppear method).
来源:https://stackoverflow.com/questions/5759465/how-do-i-automatically-load-the-keyboard-ios-sdk