打开应用程序时如何将焦点放在文本字段上?

How to focus on a text field when opening an application?

如何在打开应用程序时将焦点放在文本字段上?

Swift 4, Xcode10个, macOS

答案:

感谢@Willeke 在评论中的建议,我是这样做的:

import Cocoa
import AppKit
import Foundation
let defaults = UserDefaults.standard

class ViewController: NSViewController{

    @IBOutlet weak var addDomain: NSTextField!
    @IBOutlet weak var addSiteField: NSTextField!
    @IBOutlet weak var tableView: NSTableView!
    @IBOutlet weak var removeSite: NSSegmentedControl!

    override func viewDidAppear() {
        super.viewDidAppear()
        addDomain.window?.makeFirstResponder(addDomain)

    }

因为: https://developer.apple.com/documentation/appkit/nsresponder/1526750-becomefirstresponder

Use the NSWindow makeFirstResponder(_:) method, not becomeFirstResponder() method, to make an object the first responder. Never invoke this method directly.

在你的 viewControllerviewDidAppear

yourTextField.becomeFirstResponder()

更新:

macOS 实施 需要 使用 NSWindow makeFirstResponder!

您似乎并没有覆盖属于您的 NSViewControllerviewDidAppear,但您在其上添加了一个新功能拥有。

尝试使用:

override func viewDidAppear() {
    // Though the default implementation does nothing as of now, 
    // it is always safe to have the call to the super function in place, 
    // in case you plan to add sub-classes in between.
    super.viewDidAppear()

    addDomain.window?.makeFirstResponder(addDomain)
}