【问题标题】:Set cursor focus on TextField when form load in Objective C在Objective C中加载表单时将光标焦点设置在TextField上
【发布时间】:2012-09-14 08:43:00
【问题描述】:

我有 3 个文本字段(用户名、密码、确认密码)。当表单加载时,我希望光标在表单首次显示时在文本字段用户名中开始。请给我一些建议。提前致谢。

【问题讨论】:

    标签: objective-c cocoa textfield


    【解决方案1】:

    使用消息becomeFirstResponder,像这样:

    [self.passwordField becomeFirstResponder]
    

    【讨论】:

      【解决方案2】:

      [usernameTextField becomeFirstResponder];

      这应该会为您提供所需的结果。如果您想了解有关该机制的更多信息,可以阅读responder chain here

      编辑:

      我的错,我以为你的意思是 UITextField (Cocoa Touch)。

      使用 NSWindow makeFirstResponder: 方法,而不是这个方法,使 第一个响应者的对象。切勿直接调用此方法。

      [window makeFirstResponder:usernameTextField];
      

      【讨论】:

      • 您的文本字段是否在界面生成器中正确连接?
      • 是的,它已经连接了。我在 .h 中声明(IBOutlet NSTextField *txtUsername; 并在 .m 中合成(@synthesize txtUsername),然后我拖动连接器,但它仍然不起作用。
      • 我不相信这会有很大的不同,但是你设置了UITextField delegate吗?
      • 我在 Mac 上开发我使用 NSTextField 的应用程序
      • 旧帖子,但这对我来说非常适合使用 NSTextField。谢谢! :-)
      【解决方案3】:

      在斯威夫特中

      self.sampleUITextField.becomeFirstResponder()

      【讨论】:

        【解决方案4】:

        对于 macOS,使用 Swift 3,becomeFirstResponder() 调用必须在 viewWillAppear() 方法中。

        class myViewController {
          @IBOutlet weak var myTextField: NSTextField!
        
          override func viewDidLoad() {
            super.viewDidLoad()
          }
        
          override func viewWillAppear {
            myTextField.becomeFirstResponder()
          }
          ...
        }
        

        【讨论】:

          【解决方案5】:

          [yourTextfield becomeFirstResponder]

          【讨论】:

            【解决方案6】:

            在您的 loadViewviewDidLoad(仅在 10.10 中可用)在 super 调用之后添加以下内容

            dispatch_async(dispatch_get_current_queue(), ^{
                [self.usernameInputField becomeFirstResponder];
            });
            

            【讨论】:

              【解决方案7】:

              如果您尝试在 NSPanel(或任何其他工作表)中实现此目的并且禁用标题+边框,则无法设置焦点(请参阅 http://www.cocoabuilder.com/archive/cocoa/207749-nstextfield-will-not-become-editable-in-borderless-window.html

              在这种情况下,尝试继承工作表窗口类并覆盖 canBecomeKeyWindow 以始终返回 YES。

              【讨论】:

                猜你喜欢
                • 2011-03-04
                • 2014-08-29
                • 1970-01-01
                • 1970-01-01
                • 2011-11-13
                • 1970-01-01
                • 2011-09-29
                • 2019-07-27
                • 1970-01-01
                相关资源
                最近更新 更多