Can I change property UIReturnKeyType of UITextField dynamically?

二次信任 提交于 2019-12-04 03:08:56

Normally the returnKeyType and other properties are checked when the keyboard is displayed, but are not monitored for later updates. Try calling reloadInputViews on the text field after changing the returnKeyType, that should instruct it to refresh the keyboard settings.

JCalhoun

Unfortunately, -[reloadInputViews] will mess up keyboard input on two-byte keyboards.

Two-byte keyboards (Kanji for example) put temporary characters in the text field and require the user to hit enter a secondary keystroke to confirm the character entered. Calling -[reloadInputViews] abandons the secondary keystroke state.

I haven't yet found a solution for this scenario.

Some have proposed calling reloadInputViews on the textField to force the keyboard's return key to update. Unfortunately the keyboard resets when you call reloadInputViews on the textField, which changes it back to the textField's default, e.g., switching from number entry to email entry. You can minimize how often this happens by only calling reloadInputViews IF the returnKeyType changes.

int currentTextFieldReturnKeyType = textField.returnKeyType;
[textField setReturnKeyType:UIReturnKeyGo];
if (currentTextFieldReturnKeyType != textField.returnKeyType ) {
    [textField reloadInputViews];
}

This doesn't completely solve the problem, but minimizes it to the one keystroke where the return key changes.

As Animie said, the best way is to reloadInputViews to tell the keyboard about the changes.

You can do like this:

- (void)textFieldDidBeginEditing:(UITextField *)textField{

if(self.myTextField.editing){

      self.myTextField.editing.returnKeyType = UIReturnKeyNext;// or UIReturnKeyGo, etc.

   }
}

Somewhere in your code, in viewDidLoad for example, register for UIKeyboardWillShowNotification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

And when the keyboard shows up, you reloadInputViews:

- (void)keyboardWillShow:(NSNotification *)notification{
    [self.myTextField reloadInputViews];

}

As you all say, reloadInputViews resets the keyboard to its initial UIKeyboardType. Apple should give us an API to ask the keyboard for its keyboard type to set it back to what it was before reloading the input views.

With the new iOS8 API you can create your own keyboard returning the UIKeyboardType.

If still using iOS7 you can ask a certain keyboard child view in which state it is. Store that value and reset whenever you need to. Have a look at my source here: https://github.com/ustwo/US2KeyboardType

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!