iOS keyboard flickers when switching view controllers
I have a registration form and I want to have the keyboard always on top. The way I'm doing it now, is that when the user moves between view controllers, in viewDidLoad, the first UITextField becomes the first responder. The problem is that the keyboard flickers (disappears and then appears again) when the user moves between view controllers.
Also, related to this: I have a form with a few uitextfields. When the user presses next it goes to the next uitextfield using becomefirstresponder. When the user is in the last textfield, the keyboard button becomes "Done". Then, when the user presses it, if there's an error with the last field, it should get the focus (calls becomeFirstResponder) but that doesn't happen (nothing get's the focus and the keyboard goes down). All the other fields get the focus fine, just this last field doesn't. I've tried about everything: switching to other textfields and back. The problem is that done automatically removes the keyboard.
You should have made two separate questions for this.
First, your flickering:
I'm guessing you're using a UINavigationController. You can add an invisible UITextField somewhere in the UINavigationController, which you give focus before you switch to a new ViewController. Then, when the new ViewController has appeared ( viewDidAppear
), set the focus to the first textField as you want.
However, the entire approach is kind of hackey and I don't recommend you use it. Instead, try using several views in a scrollView, of which you change the offset when you move to the new view. This will also solve the flickering.
Second, losing firstResponder status on Done:
The done button is specifically there to indicate exactly that which it says; Done. Pressing this assumes the user is finished and that no text is left to type, thus dismissing the keyboard.
If you really want to keep the Done button, then try the following;
[lastField becomeFirstResponder]
, try [self performSelector:@selector(thisSelectorWillCallFirstResponder) withObject:nil afterDelay:1.0]
. thisSelectorWillCallFirstResponder
call [lastField becomeFirstResponder]
. This will give time for the keyboard to disappear, before making it pop up again, so it doesn't interfere with the becomeFirstResponder
call.
Another method would be to not use a Done button, but instead use the return key. You can intercept return anytime with the delegate method textFieldShouldReturn:
. There you can handle any error checking, without causing the textField to lose its focus.
上一篇: 如何在触摸UITextField之外的任何地方(swift中)关闭键盘?
下一篇: 切换视图控制器时,iOS键盘会闪烁