简体   繁体   English

如何禁用/启用 UITextField 中的返回键?

[英]How to disable/enable the return key in a UITextField?

Is there a way to programmatically enable or disable the Return Key on the UIKeyboard ?有没有办法以编程方式启用或禁用UIKeyboard上的返回键? The closest I could find is enablesReturnKeyAutomatically , but that only will tell whether to disable it at all.我能找到的最接近的是enablesReturnKeyAutomatically ,但这只会告诉是否完全禁用它。

Maybe the following code segment helps:也许以下代码段有帮助:

textfield.enablesReturnKeyAutomatically = YES;

This is publicly available in iPhone SDK in UITextInputTraits.这是在 UITextInputTraits 中的 iPhone SDK 中公开可用的。 Using this, return key will be disabled when no input text is available within text field.使用此功能,当文本字段中没有可用的输入文本时,将禁用返回键。

You can override UITextField 's hasText attribute to achieve this:您可以覆盖UITextFieldhasText属性来实现这一点:

class CustomTextField : UITextField {
    override public var hasText: Bool {
        get {
            return evaluateString(text)
        }
    }
}

Where evaluateString(_ text: String?) -> Bool checks against your needed input criteria, for example character count.其中evaluateString(_ text: String?) -> Bool根据您需要的输入条件进行检查,例如字符数。

Of course this does only work in combination with enablesReturnKeyAutomatically = true set on the UITextField .当然, enablesReturnKeyAutomatically = true于在UITextField上设置的enablesReturnKeyAutomatically = true

I am aware that my answer is neither timely nor written in Objective-C, but given that I have not been able to find an answer anywhere else and this question being routinely referred to in other threads, I think that here is the best place to post it.我知道我的回答既不及时,也不是用 Objective-C 写的,但鉴于我无法在其他任何地方找到答案,而且这个问题在其他线程中经常被提及,我认为这里是最好的地方发表它。

UITextField 's enablesReturnKeyAutomatically property can be set right in Interface Builder, just select the textfield and open the Attributes inspector. UITextFieldenablesReturnKeyAutomatically属性可以在 Interface Builder 中设置,只需选择文本字段并打开属性检查器。 As Tharindu stated, this will automatically enable and disable the return key depending on whether any text has been entered.正如 Tharindu 所说,这将根据是否输入任何文本自动启用和禁用返回键。

在此处输入图片说明

Of course, if you need to change this in code you can still set it programmatically using nameTextField.enablesReturnKeyAutomatically = true .当然,如果您需要在代码中更改它,您仍然可以使用nameTextField.enablesReturnKeyAutomatically = true编程方式设置它。

EDIT to address the downvotes:编辑以解决downvotes:

Otherwise, there is no official way to enable and disable the return key on command.否则,没有官方的方法来启用和禁用命令上的返回键。 I would recommend against trying to use private APIs to accomplish this.我建议不要尝试使用私有 API 来实现这一点。 Alternatively, you can use the textFieldShouldReturn: delegate method and put your conditional/validation there and respond accordingly.或者,您可以使用textFieldShouldReturn:委托方法并将您的条件/验证放在那里并做出相应的响应。

If you can get the UIKeyboard object itself (something not exposed in the SDK, mind you, so Apple may not be happy if you use these calls), then there's a convenient setReturnKeyEnabled: member function. 如果您可以获得UIKeyboard对象本身(SDK中未公开的内容,请注意,如果您使用这些调用,Apple可能会不高兴),那么有一个方便的setReturnKeyEnabled:成员函数。

id keyboard = [self magicallyGetAUIKeyboardInstance];
[keyboard setReturnKeyEnabled: NO];

(via Erica Sadun's dump of the 2.2 iPhone frameworks) (通过Erica Sadun转储 2.2 iPhone框架)

The implementation of magicallyGetAUIKeyboardInstance is described here . 这里描述了magicallyGetAUIKeyboardInstance的实现。

One good idea is to create one file to access this class from anywhere.一个好主意是创建一个文件以从任何地方访问此类。 Here is the code:这是代码:

UIKeyboard.h UIKeyboard.h

#import <UIKit/UIKit.h> 

@interface UIApplication (KeyboardView)

    - (UIView *)keyboardView; 

@end

UIKeyboard.m UIKeyboard.m

#import "UIKeyboard.h"

@implementation UIApplication (KeyboardView)

- (UIView *)keyboardView
{
    NSArray *windows = [self windows];
    for (UIWindow *window in [windows reverseObjectEnumerator])
    {
        for (UIView *view in [window subviews])
        {
            if (!strcmp(object_getClassName(view), "UIKeyboard"))
            {
                return view;
            }
        }
    }

    return nil;
}

@end

Now you can import and access this class from your own class:现在你可以从你自己的类中导入和访问这个类:

#import "UIKeyboard.h"

    // Keyboard Instance Pointer.
    UIView *keyboardView = [[UIApplication sharedApplication] keyboardView];

A full documentation of this class you can find here: http://ericasadun.com/iPhoneDocs/_u_i_keyboard_8h-source.html您可以在此处找到此类的完整文档: http : //ericasadun.com/iPhoneDocs/_u_i_keyboard_8h-source.html

More information you can find here: http://cocoawithlove.com/2009/04/showing-message-over-iphone-keyboard.html您可以在此处找到更多信息: http : //cocoawithlove.com/2009/04/showing-message-over-iphone-keyboard.html

My answer to the duplicate question , copied over :我对重复问题的回答,复制过来

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. OP 希望将键盘上的返回按钮“变灰”,作为给用户的视觉信号。

Here is my solution, working on iOS 13. You may have to modify the solution slightly for other iOS versions.这是我的解决方案,适用于 iOS 13。您可能需要为其他 iOS 版本稍微修改解决方案。

First, I extend UITextFieldDelegate .首先,我扩展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):然后,每当我需要禁用“返回”键时,我们可以这样做(用委托对象的变量名替换delegate ):

if let keyboard = delegate.getKeyboard(){
    keyboard.setValue(text == nil, forKey: "returnKeyEnabled")
}

Let me suggest a bit hacky solution which requires no subclassing.让我建议一个不需要子类化的有点hacky的解决方案。

extension UITextFieldDelegate {
    func setReturnKeyState(for textField: UITextField, isEnabled: Bool, delay: Double? = nil) {
        textField.enablesReturnKeyAutomatically = false
        if textField.delegate != nil {
            if let delay = delay {
                DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                    textField.setValue(isEnabled, forKeyPath: "inputDelegate.returnKeyEnabled")
                }
            } else {
                textField.setValue(isEnabled, forKeyPath: "inputDelegate.returnKeyEnabled")
            }
        }
    }
}

Usage practical sample使用实例

Define any condition, for example like this:定义任何条件,例如像这样:

private func validateInput(_ string: String?) -> Bool {
    (string?.count ?? 0) > 3
}

Call setReturnKeyState in delegate methods, for example:在委托方法中调用setReturnKeyState ,例如:

func textFieldDidBeginEditing(_ textField: UITextField) {
    setReturnKeyState(for: textField, isEnabled: validateInput(textField.text), delay: 0.1) // A bit hacky it needs delay here
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if var text = textField.text, let range = Range(range, in: text) {
        text.replaceSubrange(range, with: string)
        setReturnKeyState(for: textField, isEnabled: validateInput(text))
    }
    return true
}

Here is a technique that is available from the documented API, but it does not provide visual feedback when the enter key is disabled.这是一种可从记录的 API 中获得的技术,但在禁用 Enter 键时它不会提供视觉反馈。

- (void)setup {
    // Or in init
    self.textField.delegate = self;
}

// <UITextFieldDelegate>
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // substitute your test here
    return [textField.text rangeOfString:@"@"].location != NSNotFound;
}

Other answers here can be used with此处的其他答案可用于

[textField addTarget:self
              action:@selector(validateTextField:)
    forControlEvents:UIControlEventEditingChanged];

to provide dynamic visual feedback as the user types.在用户键入时提供动态视觉反馈。

Try to use a UITextField!尝试使用 UITextField! to receive this string and than the return are gone!接收这个字符串,然后返回就消失了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM