【问题标题】:How to disable/enable the return key in a UITextField?如何禁用/启用 UITextField 中的返回键?
【发布时间】:2010-10-21 18:14:15
【问题描述】:

有没有办法以编程方式启用或禁用UIKeyboard 上的返回键?我能找到的最接近的是enablesReturnKeyAutomatically,但这只会说明是否要禁用它。

【问题讨论】:

  • 查看我对重复问题的回答here

标签: ios objective-c xcode cocoa-touch


【解决方案1】:

让我建议一个不需要子类化的有点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")
            }
        }
    }
}

使用实际示例

定义任何条件,例如这样:

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

在委托方法中调用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
}

【讨论】:

    【解决方案2】:

    我对@9​​87654321@的回答,复制过来

    所有其他解决方案都不能回答这个问题。 OP 希望将键盘上的返回按钮“变灰”,作为给用户的视觉信号。

    这是我的解决方案,适用于 iOS 13。您可能需要针对其他 iOS 版本稍微修改解决方案。

    首先,我扩展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
        }
    

    然后,当我需要禁用“return”键时,我们可以这样做(将delegate替换为您的委托对象的变量名):

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

    【讨论】:

      【解决方案3】:

      也许以下代码段有帮助:

      textfield.enablesReturnKeyAutomatically = YES;
      

      这在 iPhone SDK 中的 UITextInputTraits 中公开可用。使用这个,当文本字段中没有可用的输入文本时,返回键将被禁用。

      【讨论】:

      • 在 Swift 中:textfield.enablesReturnKeyAutomatically = true
      • 可能听起来很傻,但我来到这里时想要这个答案。就像我想很多人一样,我盲目地点击了谷歌出现的第一个链接,完全跳过了这个问题,阅读了前几个答案
      【解决方案4】:

      尝试使用 UITextField!接收这个字符串然后返回就没有了!

      【讨论】:

        【解决方案5】:

        这是一种可从文档化 API 获得的技术,但在禁用回车键时它不会提供视觉反馈。

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

        这里的其他答案可以和

        一起使用
        [textField addTarget:self
                      action:@selector(validateTextField:)
            forControlEvents:UIControlEventEditingChanged];
        

        在用户键入时提供动态视觉反馈。

        【讨论】:

          【解决方案6】:

          您可以覆盖UITextFieldhasText 属性来实现此目的:

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

          evaluateString(_ text: String?) -&gt; Bool 会根据您需要的输入条件(例如字符数)进行检查。

          当然,这只适用于在UITextField 上设置的enablesReturnKeyAutomatically = true

          我知道我的答案既不及时,也不用 Objective-C 编写,但鉴于我无法在其他任何地方找到答案,而且这个问题经常在其他线程中被提及,我认为这里是发布它的最佳位置。

          【讨论】:

          • 这可行,但会导致密码键盘附件永远不会消失。
          • 有什么方法可以异步执行此操作吗?
          【解决方案7】:

          UITextFieldenablesReturnKeyAutomatically 属性可以在 Interface Builder 中设置,只需选择文本字段并打开属性检查器。正如 Tharindu 所说,这将根据是否输入任何文本自动启用和禁用返回键。

          当然,如果您需要在代码中更改它,您仍然可以使用nameTextField.enablesReturnKeyAutomatically = true 以编程方式设置它。

          编辑以解决反对意见:

          否则,没有官方方法可以启用和禁用命令中的返回键。我建议不要尝试使用私有 API 来完成此操作。或者,您可以使用 textFieldShouldReturn: 委托方法并将您的条件/验证放在那里并做出相应的响应。

          【讨论】:

            【解决方案8】:

            一个好主意是创建一个文件来从任何地方访问这个类。代码如下:

            UIKeyboard.h

            #import <UIKit/UIKit.h> 
            
            @interface UIApplication (KeyboardView)
            
                - (UIView *)keyboardView; 
            
            @end
            

            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
            

            现在您可以从自己的类中导入和访问该类:

            #import "UIKeyboard.h"
            
                // Keyboard Instance Pointer.
                UIView *keyboardView = [[UIApplication sharedApplication] keyboardView];
            

            您可以在此处找到此类的完整文档: http://ericasadun.com/iPhoneDocs/_u_i_keyboard_8h-source.html

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

            【讨论】:

            • App Store 拒绝概率:100%
            • 我认为这不值得拒绝。我们只是迭代子视图并选择我们喜欢的。然而,它很方便,并没有回答关于禁用返回键的问题。
            • 这是一个非常糟糕的主意...除了 Apple 拒绝您之外,系统设置可能会在您不知情的情况下更改并破坏此解决方案。
            猜你喜欢
            • 2015-11-20
            • 2016-05-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多