问题
I am looking to enable the return key of a UITextField
keyboard if (and only if) the user inputs a valid email address.
I have tried a solution that dates back from 2009 which uses the private method setReturnKeyEnabled
. Unfortunately, this method does not seem to exist anymore:
No known instance method for selector 'setReturnKeyEnabled:'
How can I programmatically enable and disable the return key of a keyboard?
回答1:
All the other solutions do not answer the question. OP wants to "gray" out the return button on the keyboard as a visual signal to the user.
Here is my solution, working on iOS 13. You may have to modify the solution slightly for other iOS versions.
First, I extend UITextFieldDelegate
.
func getKeyboard() -> UIView?
{
for window in UIApplication.shared.windows.reversed()
{
if window.debugDescription.contains("UIRemoteKeyboardWindow") {
if let inputView = window.subviews
.first? // UIInputSetContainerView
.subviews
.first // UIInputSetHostView
{
for view in inputView.subviews {
if view.debugDescription.contains("_UIKBCompatInputView"), let keyboard = view.subviews.first, keyboard.debugDescription.contains( "UIKeyboardAutomatic") {
return keyboard
}
}
}
}
}
return nil
}
Then, whenever I need to disable the "return" key, we can do (replace delegate
with the variable name of your delegate object):
if let keyboard = delegate.getKeyboard(){
keyboard.setValue(text == nil, forKey: "returnKeyEnabled")
}
回答2:
- Set the delegate on your UITextField
- For your delegate instance (the one you just set that conforms to UITextFieldDelegate), implement:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
.
There are other callbacks in the delegate, such as textField:shouldChangeCharactersInRange:replacementString:
that may be of interest to you, if you're trying to keep the textField always "correct" and not allow the user to continue typing after the textfield has become erroneous wrt to your preferred formatting / validation. Definitely worth taking a look at the documentation for UITextFieldDelegate for all your possible callbacks.
回答3:
You don't really enable or disable the return key. Instead, if the user presses the return key, the delegate method -textFieldShouldReturn:
gets called. If you want to hide the keyboard in that case, you have to call -resignFirstResponder
on the text field, in your delegate method.
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/index.html
来源:https://stackoverflow.com/questions/30425464/grey-out-return-key-programmatically